评论belongs_to几个模型之一

bri*_*ran 0 ruby activerecord ruby-on-rails polymorphic-associations ruby-on-rails-3

我的情况是有几种不同的模型可以有评论.试图找出关系:

Post
  has_many :comments

Update
  has_many :comments

Comment
  belongs_to EITHER :post OR :update (but not both)????
Run Code Online (Sandbox Code Playgroud)

什么是建立评论关系的正确方法?我希望能够打电话Post.commentsUpdate.comments

mu *_*ort 5

闻起来像一个多态关联:

通过多态关联,模型可以属于单个关联上的多个其他模型.例如,您可能拥有属于员工模型或产品模型的图片模型.

所以你想要这样的东西:

class Comment < ActiveRecord::Base
  belongs_to :commentable, :polymorphic => true
end

class Post < ActiveRecord::Base
  has_many :comments, :as => :commentable
end

class Update < ActiveRecord::Base
  has_many :comments, :as => :commentable
end
Run Code Online (Sandbox Code Playgroud)

您必须在数据库中设置一些内容才能使其正常工作.有关您需要的列的详细信息,请参阅" Active Record Associations Guide"的" Polymorphic Associations"部分.