【发布时间】:2021-09-17 03:03:08
【问题描述】:
我有一个用户自加入关联。 这是我目前的数据
我的用户模型
User.rb
class User < ApplicationRecord
belongs_to :mother, class_name: "User", optional: true
belongs_to :father, class_name: "User", optional: true
end
我可以在 Rails 控制台中执行以下操作。
irb(main):001:0> user = User.find(1)
(0.4ms) SELECT sqlite_version(*)
User Load (0.3ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT ? [["id", 1], ["LIMIT", 1]]
=> #<User id: 1, name: "rj", mother_id: 3, father_id: 2>
irb(main):002:0> user.father
User Load (0.1ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT ? [["id", 2], ["LIMIT", 1]]
=> #<User id: 2, name: "father", mother_id: 4, father_id: 5>
irb(main):003:0> user.father.father
User Load (0.1ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT ? [["id", 5], ["LIMIT", 1]]
=> #<User id: 5, name: "grandfather", mother_id: nil, father_id: nil>
简而言之,如果我做user.father.father或user.father.mother,我可以得到rj的父亲的父亲(祖父)和rj的父亲的母亲(祖母)的对象
有没有办法让我创建一个别名,例如 user.grandfather 和 user.grandmother 以获得相同的结果?
【问题讨论】:
-
您的 has_one 声明将被忽略,可以删除,JFYI。
标签: ruby-on-rails ruby database model self-join