Versuchen Sie folgendes:
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
So können Sie (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
Um retreive Kommentare aus der Datenbank aus einem Profil, verwenden Sie diesen Trick:
# 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
Nicht getesteter Code!
sehen hier für weitere Informationen und Erläuterungen, Why can you not have a foreign key in a polymorphic association?