nishimura.clubnishimura.club

Rails 自己結合

作成日
2021-10-14
更新日
2021-10-14

設定

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

取得

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

FactoryBot

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

ridgepole

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

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

Related

Tags

Rails

Share