【问题标题】:Defining table name for has_many self joins in rails?在rails中为has_many自连接定义表名?
【发布时间】:2012-01-05 02:41:13
【问题描述】:

我希望设置嵌套 cmets,并希望使用自连接来设置。

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 是到达子级的外键?

【问题讨论】:

    标签: sql ruby-on-rails activerecord


    【解决方案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
    

    我建议你使用插件来实现这个功能。比如 awesome_nested_set 或acts_as_tree。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-07
      • 2020-03-22
      • 1970-01-01
      • 1970-01-01
      • 2014-02-14
      相关资源
      最近更新 更多