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

Chorder · July 17, 2018 · Last by Chorder replied at July 17, 2018 · 1136 hits

需要建立一个用户分组模型,其中每个分组又包含多个子分组。 这样在创建种子数据的时候,因为 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

Reply to pinewong

解决了,感谢! 😘

Chorder closed this topic. 17 Jul 14:32
You need to Sign in before reply, if you don't have an account, please Sign up first.