Defining table name for has_many self joins in rails?

两盒软妹~` 提交于 2019-12-11 12:41:47

问题


I wish to set up nested comments, and want to use self-join to set this up.

class Comment < ActiveRecord::Base

has_many :children, :class_name => 'Comment'

#...
end

Now, what sql table structure would I use to set up the has_many self-join?

I'm assuming something like this:

comment_to_comments:
parent_id integer
child_id integer

How do I tell rails to use this table? How do I tell rails that parent_id is the foreign key to reach the parent and the child_id is the foreign key to reach the child?


回答1:


create_table :comments do |t|
  t.integer :parent_id
end

class Comment < ActiveRecord::Base
  has_many :children, :class_name => "Comment", :foreign_key => :parent_id
  belongs_to :parent, :class_name => "Comment"

end

I suggest you use plugin to implement this feature.like awesome_nested_set or acts_as_tree.



来源:https://stackoverflow.com/questions/8736955/defining-table-name-for-has-many-self-joins-in-rails

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