我只是尝试了您想要实现的目标。这是users 表的迁移:
create_table :users do |t|
t.string :name
t.references :user_a
t.references :user_b
t.timestamps
end
请注意这如何生成以下schema.rb
create_table "users", force: :cascade do |t|
t.string "name"
t.integer "user_a_id"
t.integer "user_b_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["user_a_id"], name: "index_users_on_user_a_id"
t.index ["user_b_id"], name: "index_users_on_user_b_id"
end
在用户模型中,我有
class User < ApplicationRecord
has_one :user_a, class_name: "User", foreign_key: "user_a_id"
has_one :user_b, class_name: "User", foreign_key: "user_b_id"
end
迁移后,我可以执行rails console
以下操作:
User.create(
name: "inception_user",
user_a: User.create(name: "Adam"),
user_b: User.create(name: "Berta")
)
inception_user = User.find_by_name "inception_user"
inception_user.user_a.name
=> "Adam"
inception_user.user_b.name
=> "Berta"
使用此设置一切正常。如果您还有问题,请发表评论!
有关自加入的更多信息:http: //guides.rubyonrails.org/association_basics.html#self-joins