Rails 自己結合

updated Oct 14, 2021created Oct 14, 2021

設定

user.rb
has_many :childs, class_name: "User", foreign_key: "parent_id" belongs_to :parent, class_name: "User", optional: true

取得

rb
user = User.find(1) user.childs # 子を取得 user.parent # 親を取得

FactoryBot

rb
# 親  parent = FactoryBot.create(:user) # 子 ambassador_child = FactoryBot.create( :user, parent_id: parent )

ridgepole

rb
t.integer "parent_id", null: true, commnet: "親のID" t.index ["parent_id"], name: "parent_id"

Active Record の関連付け - Railsガイド