在Devise Rails中注册新用户之前更新服装字段



我有一个Rails应用程序,并使用Devise在应用程序中进行身份验证。此 Rails 应用程序处于 API 模式。我在设计用户模型中添加了一些服装字段:

## Costume fields
field :ip, type: String
field :role, type: String , default: 'client'

如您所见,我想在设计的注册操作期间添加用户的IP地址。我想告诉设计,当您收到新的"注册"请求时,请在将用户添加到数据库之前,获取用户 IP 并将其添加到字段中,然后将新用户保存到数据库中,如下所示:

{
  email: 'test@example.com',
  encrypted_password: "sg4rgtgesrre5erghtr5etrgtrrergre55trgf....",
  ip: '1.2.2.1'    // The user rote IP
}

希望您已经设置了设计控制器

在用户的注册控制器中,您可以修改脚本

class Users::RegistrationsController < Devise::RegistrationsController
 def create
  build_resource(sign_up_params)
  resource.ip = '1.1.1.1'
  resource.save
  yield resource if block_given?
  if resource.persisted?
   ....# rest of the create action code
 end

但这不会在保存之前将 IP 保存到数据库....但 IP 值将添加到用户对象中以便进一步保存。

您需要

覆盖Devise::RegistrationController中的修改创建操作才能完成这项工作。

https://github.com/plataformatec/devise/blob/40f02ae69baf7e9b0449aaab2aba0d0e166f77a3/app/controllers/devise/registrations_controller.rb#L17

您的主要目标是修改sign_up_params内容。您可以通过两种方式进行操作:

  1. 你可以创建你自己的参数,比如

    def user_sign_up_params
     sign_up_params.merge ip: request.ip
    end
    

    并更改上面的行build_resource(user_sign_up_params)

  2. 您可以在像build_resource(sign_up_params.merge(ip: request.ip))这样的地方添加 IP

最新更新