新手问题 ActiveRecord 自关联 (自联结) 模型中,如何创建第一个对象?

Chorder · 2018年07月17日 · 最后由 Chorder 回复于 2018年07月17日 · 1136 次阅读

需要建立一个用户分组模型,其中每个分组又包含多个子分组。 这样在创建种子数据的时候,因为 parent_group_id 此时为空,第一条数据是无法创建成功的,请问应该采用那种方法? 代码如下:

Seed:

UserGroup.create([
    { name: "全部用户" },
])

Model:

class UserGroup < ApplicationRecord
  has_many :sub_groups, class_name: "UserGroup", foreign_key: "parent_group_id"
  belongs_to :parent_group, class_name: "UserGroup"
  has_and_belongs_to_many :users
end

Migration:

class CreateUserGroups < ActiveRecord::Migration[5.2]
  def change
    create_table :user_groups do |t|
      t.references :parent_group, index: true
      t.string :name

      t.timestamps
    end

    create_table :user_groups_users, id: false do |t|
      t.belongs_to :user_group, index: true
      t.belongs_to :user, index: true
    end

  end

end

belongs_to :parent_group, class_name: "UserGroup", optional: true

pinewong 回复

解决了,感谢! 😘

Chorder 关闭了讨论。 07月17日 14:32
需要 登录 后方可回复, 如果你还没有账号请 注册新账号