我有两个表,“内容”和“个人资料”可以评论和评级。我已经看过使用多态关联并决定反对它。如果我使用多态关联,表“rating”和“comments”都会有这个功能。
这是否可以通过具体的超级实现来实现?如果是这样,我该怎么做?
答案 0 :(得分:1)
您正在混合联接中的列。它应该是这样的:
find(self.id, :joins => "JOIN commentables cm ON (profiles.commentable_id = cm.id)
LEFT OUTER JOIN comments c ON (cm.id = c.commentable_id)")
答案 1 :(得分:0)
试试这个:
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
这使您能够(脚本/控制台):
# 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 = "Inspector.Gadget@example.com"
c.commentable_id = p.commentable_id
c.save!
end
要从配置文件中检索数据库中的注释,请使用此技巧:
# 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
未经测试的代码!
请点击此处了解更多详情和解释,Why can you not have a foreign key in a polymorphic association?
答案 2 :(得分:0)
如果我错了,请纠正我,但你不能在Profiles.rb中做到这一点
def comments
Comments.find(:all, :conditions => ["commentable_id = ?", self.commentable_id])
end