【问题标题】:rails: self-referential associationrails:自引用关联
【发布时间】:2010-06-12 15:55:45
【问题描述】:

我的需求很简单:我有一个 Tip 表来接收 cmets,也有 cmets 来接收 cmets。

为了检索存储在同一个表 (cmets) 中的每条评论,我为 cmets 上的 cmets 创建了另一个键:“inverse_cmets”。

我尝试通过自引用关联来使用一个 cmets 表。有些资源似乎将不止一张桌子带入了与我的需求不同的桌子。所以我想出了以下 cmets 建模:

class Comment < ActiveRecord::Base
  belongs_to :tip 
  belongs_to :user
  has_many :mycomments, 
           :through => :inverse_comments,
           :source => :comment
end

显然这里缺少一些东西,但我无法弄清楚。 有人可以启发我吗:

我需要做哪些更改才能使模型正常工作?

谢谢。

【问题讨论】:

    标签: ruby-on-rails self-reference


    【解决方案1】:

    我相信你应该使用polymorphic association

    为此,您需要在 comments 表中添加 commentable_idcommentable_type。你的模型应该是这样的:

    class Comment < ActiveRecord::Base
       belongs_to :user
       belongs_to :commentable, :polymorphic => true    
       has_many :comments, :as => :commentable
    end 
    
    class Tip < ActiveRecord::Base 
       has_many :comments, :as => :commentable
    end
    

    这样你就可以使用

    @tip.comments
    @comment.comments
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多