Essayez ceci:
class Commentable < ActiveRecord::Base
has_many :comments
has_one :profile, :content
end
class Comment < ActiveRecord::Base
belongs_to :commentable
end
class Content < ActiveRecord::Base
belongs_to :commentable
end
class Profile < ActiveRecord::Base
belongs_to :commentable
end
Cela vous permet de (script/console):
# every time you create a profile, link it to the
# commentable row associated to this profile instance
cid = Commentable.create().id
p = Profile.create(:name => "Inspector Gadget",
:commentable_id => cid)
# when creating the comment, assign the commentable_id
# to link it to a Profile comment
Comment.new do |c|
c.body = "go go gadget"
c.email = "[email protected]"
c.commentable_id = p.commentable_id
c.save!
end
Pour récupérer les commentaires de la base de données à partir d'un profil, utilisez cette astuce:
# Profile.rb
# instead of doing a has many through,
# we can just use instance method with custom join.
def comments
find(self.id, :joins => "JOIN commentables cm ON (profiles.id = cm.id)
LEFT OUTER JOIN comments c ON (cm.id = c.commentable_id)")
end
Code non testé!
voir ici pour plus de détails et explaination, Why can you not have a foreign key in a polymorphic association?