繁体   English   中英

如何添加信息以设计@resource

[英]How to add information to devise @resource

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

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

如何向此变量添加信息? 我想到了诸如...

contact_from_other_app = Contact.find(@resource.contact_id_from_other_app)

@resource.firstname = contact_from_other_app.firstname

但是我必须把那个代码放在哪里,具体怎么放?

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

  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

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

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

在用户模型中

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

然后在视图中可能出现以下情况

<%= @resource.contact.firstname %>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM