在我的rails应用程序中,除了电子邮件之外,有关用户的信息(如名字或性别(不会存储在用户中。它们可以通过其他应用程序的rest api接收。
在设计视图中,用户信息可以通过@resource变量来显示。
如何向该变量添加信息?我想到了。。。
contact_from_other_app = Contact.find(@resource.contact_id_from_other_app)
@resource.firstname = contact_from_other_app.firstname
但我必须把代码放在哪里,具体是怎么放的?
您可以通过几种方式在中实现这一点。
- 委派到关联
class User < ApplicationRecord
has_one :contact
delegate :firstname, :gender, to :contact, allow_nil: true
end
然后你可以打电话给
@resource.firstname # equivalent of @resource.contact&.firstname
@resource.gender # equivalent of @resource.contact&.gender
- 设置属性访问器
class User < ApplicationRecord
attr_accessor :firstname, :gender
end
contact_from_other_app = Contact.find(@resource.contact_id_from_other_app)
@resource.firstname = contact_from_other_app.firstname
最后我发现,我在代码中已经有了这个功能:((
class Contact < OtherAppApiResource
def firstname
attributes["firstname"]
end
在用户模型中
class User < ApplicationRecord
def contact
@contact ||= Contact.get(other_app_contact_id)
end
然后在视图中,以下是可能的
<%= @resource.contact.firstname %>