简体   繁体   中英

Saving custom fields in devise User model in Rails 4.1.4

I just followed this guide to add the columns 'firstname' and 'secondname' to the Devise User Model with the following commands.

rails generate migration add_firstname_to_user firstname:string
rails generate migration add_secondname_to_user secondname:string

and I aplied the changes with:

rake db:migrate

It worked right, because I can see those fields through the console with User.all, however the problem I have now is that I don't see the attr_accessible field in app/model/user.rb.

So I just added the following lines:

<div><%= f.label :first_name %><br />
  <%= f.text_field :firstname, autofocus: true %></div>

<div><%= f.label :second_name %><br />
  <%= f.text_field :secondname, autofocus: true %></div>

in new.html.erb in app/views/devise/registrations, but it isn't working, because I noticed that the firstname and secondname attributes are nil on the users I registered.

What can I do?, I guess is something about the attr_accessible step, but I couldn't find it.

Any help will be appreciated.

For custom fields 'first name' and 'second name', you can make them accessible by adding following code in your application controller

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

  protected

  def configure_permitted_parameters
     devise_parameter_sanitizer.for(:sign_in) { |u| u.permit(:username, :email, :firstname, :secondname) }
     devise_parameter_sanitizer.for(:sign_up) { |u| u.permit(:username, :email, :password, :password_confirmation, :firstname, :secondname) }
     devise_parameter_sanitizer.for(:account_update) { |u| u.permit(:username, :email, :password, :password_confirmation, :current_password, :firstname, :secondname) }
  end
end

You can add more custom fields and permitting them here, Change the code correspondingly as per your needs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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