【问题标题】:alias for chain methods in railsrails 中链方法的别名
【发布时间】:2021-09-17 03:03:08
【问题描述】:

我有一个用户自加入关联。 这是我目前的数据

Click to view data table

我的用户模型
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.fatheruser.father.mother,我可以得到rj的父亲的父亲(祖父)和rj的父亲的母亲(祖母)的对象

有没有办法让我创建一个别名,例如 user.grandfatheruser.grandmother 以获得相同的结果?

【问题讨论】:

  • 您的 has_one 声明将被忽略,可以删除,JFYI。

标签: ruby-on-rails ruby database model self-join


【解决方案1】:

在 User.rb 模型中,添加以下方法

def paternal_grandfather
   father&.father
end

def paternal_grandmother
  father&.mother
end

def maternal_grandfather
   mother&.father
end

def maternal_grandmother
  mother&.mother
end

或者,在组合形式中,我们可以将方法用作

def grandfather
  father&.father || mother&.father
end

def grandmother
  father&.mother || mother&.mother
end

将其用作user.grandfatheruser.grandmother

【讨论】:

  • 但是妈妈的爸爸不也是爷爷吗?
  • 我更新了答案,希望对你有用。
  • @spickermann 是的,但为了简化,我只是以父亲一方为例,而不是父母双方!
  • @ShamsulHaque 感谢您的这种方法,它可以工作,但会像控制台显示的那样创建两个 SQL 查询,这将访问数据库两次。不确定在实际情况下是否建议这样做。
【解决方案2】:
class User < ApplicationRecord
  belongs_to :mother, class_name: "User", optional: true
  belongs_to :father, class_name: "User", optional: true
  has_one :grandfather, through: :father, source: :father
  has_one :grandmother, through: :father, source: :mother
end

【讨论】:

  • 人们有两组祖父母。
  • OP 明确定义了祖父:user.father.father 和祖母user.father.mother,所以基本上没问题,虽然在英语中可能不是。 @DaveNewton
  • @DaveNewton 是的,但为了简化,我只是以父亲一方为例,而不是父母双方!
  • @LamPhan 谢谢你的回答,这就是我要找的!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多