【问题标题】:Comment belongs_to one of several models评论belongs_to 几个模型之一
【发布时间】:2011-12-01 05:36:13
【问题描述】:

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

Post
  has_many :comments

Update
  has_many :comments

Comment
  belongs_to EITHER :post OR :update (but not both)????

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

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-3 activerecord polymorphic-associations


    【解决方案1】:

    闻起来像polymorphic association:

    使用多态关联,一个模型可以在一个关联上属于多个其他模型。例如,您的图片模型可能属于员工模型或产品模型。

    所以你想要这样的东西:

    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
    

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

    【讨论】:

    • +1 像往常一样 :-) 感谢您提供指向费曼系列的链接!
    • @Tilo:谢谢,RPF 是我的英雄之一,Sagan Series 也值得花一些时间。
    • 准确 - 正是它看起来像是为多态创建的
    • commentable_id 和 commentable_type 怎么样 - 我应该在视图中使用隐藏字段设置它们还是有更好的方法
    • @brittohalloran:您可以或使用post.create_comment 或post.build_comment 方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-09
    • 1970-01-01
    • 1970-01-01
    • 2018-08-17
    相关资源
    最近更新 更多