admin

定义has_many self联接的表名是否在rails中?

sql

我希望设置嵌套注释,并希望使用自连接进行设置。

class Comment < ActiveRecord::Base

has_many :children, :class_name => 'Comment'

#...
end

现在,我将使用哪种sql表结构来设置has_many自联接?

我假设是这样的:

comment_to_comments:
parent_id integer
child_id integer

我如何告诉Rails使用此表?我如何告诉Rails parent_id是到达父级的外键,child_id是到达子级的外键?


阅读 176

收藏
2021-07-01

共1个答案

admin

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

我建议您使用插件来实现此功能,例如awesome_nested_set或acts_as_tree。

2021-07-01