简体   繁体   English

使用 devise_token_auth 自定义用户属性

[英]Custom user attributes with devise_token_auth

I have created a new API using rails/edge and I'm using devise with the devise_token_auth which has generated me a user model.我使用 rails/edge 创建了一个新的 API,我正在使用devisedevise_token_auth ,它为我生成了一个用户模型。

My question is this, after migrating and adding new attributes to the User model how do I return this in the JSON response, currently being generated by devise_token_auth?我的问题是,在向 User 模型迁移和添加新属性后,如何在 JSON 响应中返回它,目前由 devise_token_auth 生成?

This is what you need to to in order to permit custom attributes for the Devise model (eg User model)为了允许设计模型(例如User模型)的自定义属性,您需要这样做

class ApplicationController < ActionController::Base    
  before_action :configure_permitted_parameters, if: :devise_controller?

  protected

  def configure_permitted_parameters
    # for user account creation i.e sign up
    devise_parameter_sanitizer.permit(:sign_up, keys: [:first_name, :last_name])
    # for user account update
    # where bank_name and bank_account are nested attributes in the User model
    devise_parameter_sanitizer.permit(:account_update, keys: [:first_name, :last_name, bank_attributes: [:bank_name, :bank_account]])
  end
end

source of this solution 此解决方案的来源

As mentioned in the comment above.正如上面评论中提到的。 So far my best solution is to create a separate UserDetails model, serialize that then make a separate call to it after auth to populate the extra user data.到目前为止,我最好的解决方案是创建一个单独的 UserDetails 模型,序列化然后在 auth 后单独调用它以填充额外的用户数据。

Which does actually seem quite nice as it keeps the auth clean.这实际上看起来很不错,因为它保持了身份验证的清洁。

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

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