问题
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