简体   繁体   中英

Custom user fields using devise

I'm using devise and I want to add the fields first_name and last_name to the sign_up form. After creating the respective columns, I tried to sign_up with the new form, but the values of the new fields in DB were nil.

After that I created this controller:

class RegistrationsController < Devise::RegistrationsController

  private

      def sign_up_params
        params.require(:user).permit(:first_name, :last_name, :email, :password, :password_confirmation)
      end

      def account_update_params
        params.require(:user).permit(:first_name, :last_name, :email, :password, :password_confirmation, :current_password)
      end
end

But I still get nil in the columns first_name and last_name. Am I missing something?

The form:

<h2>Sign up</h2>

<%= form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %>
  <%= devise_error_messages! %>

  <div><%= f.label :first_name %><br />
    <%= f.text_field :first_name %></div>

  <div><%= f.label :last_name %><br />
    <%= f.text_field :last_name %></div>

  <div><%= f.label :profile_name %><br />
    <%= f.text_field :profile_name %></div>

  <div><%= f.label :email %><br />
  <%= f.email_field :email, autofocus: true %></div>

  <div><%= f.label :password %> <% if @validatable %><i>(<%= @minimum_password_length %> characters minimum)</i><% end %><br />
    <%= f.password_field :password, autocomplete: "off" %></div>

  <div><%= f.label :password_confirmation %><br />
    <%= f.password_field :password_confirmation, autocomplete: "off" %></div>

  <div><%= f.submit "Sign up" %></div>
<% end %>

<%= render "devise/shared/links" %>

did you add devise_for :users, :controllers => { registrations: 'devise/registrations' } in your routes file ? If not then add it in your routes file. Other things are looks Okay

1 option. I think adding the following to application_controller.rb would eliminate the issue (instead of overridding the devise's controller):

private

  def configure_devise_params
    devise_parameter_sanitizer.for(:sign_up) do |u|
      u.permit(:first_name, :last_name, :email, :password, :password_confirmation)
    end
    devise_parameter_sanitizer.for(:account_update) do |u|
      u.permit(:first_name, :last_name, :email, :password, :password_confirmation)
    end
  end

2 option. Check passing the controllers: { registrations: 'devise/registrations' } block do devise_for :users line in routes.rb

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