0

在我的 Rails 应用程序中,除了电子邮件之外,关于用户的信息(例如名字或性别)不会存储在用户中。它们可以通过其他应用程序的 rest api 接收。

在设计视图中,用户信息可以通过@resource 变量显示。

如何向此变量添加信息?我想到类似...

contact_from_other_app = Contact.find(@resource.contact_id_from_other_app)

@resource.firstname = contact_from_other_app.firstname

但是我必须把该代码放在哪里以及如何准确?

4

2 回答 2

0

您可以通过几种方式做到这一点。

  1. 代表协会
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
  1. 设置属性访问器
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
于 2020-09-28T10:59:41.360 回答
0

最后我发现,我在代码中已经有了这个功能:)))

class Contact < OtherAppApiResource
  def firstname
    attributes["firstname"]
  end

在用户模型中

class User < ApplicationRecord
  def contact
    @contact ||= Contact.get(other_app_contact_id)
  end

然后在视图中以下是可能的

<%= @resource.contact.firstname %>
于 2020-09-28T12:32:30.963 回答