Rails - 是否可以在模型中为其嵌套属性设置快捷方式?

Rails - is it possible to have a shortcut within a model for its nested attributes?

这可能是一个愚蠢的问题,但它让我的脑袋绞尽脑汁了一段时间...

所以.. 我有 2 个模型:(1) 用户和 (2) 个人资料。个人资料通过以下关系与用户相关联:

(1) user has_one :profile
(2) profile belongs_to user

这是设计系统中用户和配置文件的标准关系。无论如何,通常我通过以下嵌套属性访问用户名:

"user.profile.name"

是否可以在用户模型中创建一个链接到配置文件模型中该属性的 "virtual" 属性?我想通过“user.name”调用“user.profile.name”。

是的,有:delegate

class User < ...
  delegate :name, to: :profile

   # The rest of your class
end

这会将配置文件 class 中的 name 方法公开给您的用户 class