我有两个可以评论和评分的表格,“内容”和“个人资料”。我已经研究过使用多态关联并决定反对它。如果我要使用多态关联,表“评分”和“评论”都将具有此功能。
这可以通过具体的超表实现来实现吗?如果是这样,我该怎么做?
我有两个可以评论和评分的表格,“内容”和“个人资料”。我已经研究过使用多态关联并决定反对它。如果我要使用多态关联,表“评分”和“评论”都将具有此功能。
这可以通过具体的超表实现来实现吗?如果是这样,我该怎么做?
You're mixing up columns on the join. It should be this:
find(self.id, :joins => "JOIN commentables cm ON (profiles.commentable_id = cm.id)
LEFT OUTER JOIN comments c ON (cm.id = c.commentable_id)")
尝试这个:
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
未经测试的代码!
有关更多详细信息和说明,请参见此处,为什么在多态关联中不能有外键?
如果我错了,请纠正我,但你不能在 Profiles.rb 中这样做吗
def comments
Comments.find(:all, :conditions => ["commentable_id = ?", self.commentable_id])
end