rails: self-referential association

半世苍凉 提交于 2019-12-12 09:23:42

问题


My needs are very simple: I have a Tip table to receive comments and have comments to receive comments, too.

To retrieve each comment that is stored in the same table (comments), I created another key for the comments on comments: "inverse_comments".

I tried to use one comments table by using self-referntial association. Some resources seem to bring more than one table into the piture which are diffent from my needs. So I came up whth the following modeling for comments:

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

Apparently something is missing here but I cannot figure it out. Could some one enlighten me on this:

what changes I need to do to make the model work?

thanks.


回答1:


I believe you should use a polymorphic association.

For that you'll need to add a commentable_id and a commentable_type on your comments table. And your models should look like:

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

This way you can use

@tip.comments
@comment.comments


来源:https://stackoverflow.com/questions/3029227/rails-self-referential-association

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!