【发布时间】:2020-03-04 04:15:37
【问题描述】:
我正在尝试弄清楚如何在 Rails 中进行自引用关联。我是 Rails 初学者。
基本上,我有一个模型Group。每个组可以有许多子组。我觉得我已经尝试了所有方法,但我无法让加入工作。
我现在拥有的是
# GroupSubGroup Model
class GroupSubGroup < ApplicationRecord
belongs_to :group
belongs_to :sub_group, class_name: 'Group'
end
然后我的组模型看起来像
has_many :group_sub_groups
has_many :sub_groups, foreign_key: :sub_group_id, through: :group_sub_groups, class_name: 'GroupSubGroup'
has_many :groups, through: :sub_groups
has_many :groups, class_name: 'GroupSubGroup'
我的迁移看起来像
create_table :group_sub_groups do |t|
t.integer :group_id, index: true, foreign_key: { to_table: :groups }
t.references :sub_group, index: true, foreign_key: { to_table: :groups }
t.timestamps
end
我的主要问题是我可以使用parent_group.sub_groups.new 在连接表中添加一个新的GroupSubGroup 行,但是当我检索父组并循环它的sub_groups 时,没有一个实例属于@987654328 @class,因此没有任何方法。
例如
Group.all.each do |group|
group.sub_groups.each do |s|
puts "#{s.name} is a sub group for #{group.name}"
end
end
引发undefined method 'name' 错误。
【问题讨论】:
-
您的子组是否有
name作为列?假设您正确地进行迁移,您给出的错误消息只会提示您的子组没有name作为列。
标签: ruby-on-rails activerecord