devise User model custom field always nil

2019-07-29 09:07发布

问题:

I am using devise on my rails 4 project, I have 3 custom fields in my User model,

  • company_name
  • phone_number
  • name

When I create a new User at rails console with the following code

u = User.new(email:'example@example.com', company_name: "xxxxxx", phone_number: "12345678", name: "Test Name", password: 'asdfadsf')

Then print out this instance, it shows correctly

#<User id: nil, email: "example@example.com", encrypted_password: "$2a$10$xf9N0xw9zrGBDngD48IdRO9AEUkAJH1/XjOy0dFZTd0L...", reset_password_token: nil, reset_password_sent_at: nil, remember_created_at: nil, sign_in_count: 0, current_sign_in_at: nil, last_sign_in_at: nil, current_sign_in_ip: nil, last_sign_in_ip: nil, created_at: nil, updated_at: nil, organization_id: nil, username: nil, admin: nil, profile_img: nil, tagline: nil, name: "Test Name", status: 1, country_code: nil, phone_number: "12345678", company_name: "xxxxxx">

Then I access devise built in fields, it show the value correctly

u.email => "example@example.com"

but when I try to access the custom field, like company_name, it shows nil instead

u.company_name => nil

Anyone has a clue on this?

回答1:

You should permit those custom attributes through strong parameters.

The devise wiki has some useful examples, such as:

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

  protected

  def configure_permitted_parameters
    devise_parameter_sanitizer.for(:sign_up) << [:name, :company_name, :phone_number]
  end
end

Or you can use this:

def configure_permitted_parameters
  devise_parameter_sanitizer.for(:sign_up) { |u| u.permit(:email, :name, :company_name, :phone_number, :password, :password_confirmation) }
end

Or if you don't want any restrictions:

def configure_permitted_parameters
  devise_parameter_sanitizer.for(:sign_up) { |u| u.permit! }
end


回答2:

I have found the problem. I have put the following line in the user model which override company_name, phone_number methods just remove these lines make it works.

attr_accessor :company_name, :country_code, :phone_number

def company_name
end

def phone_number
end

def country_code
end