I have a default sign up page generated by Devise, and another that is the landing page for users not signed in.
For both, I would like to allow users to choose a profile name when they sign up, but not require it. How can I do this?
Devise registrations_controller.rb
class Users::RegistrationsController < Devise::RegistrationsController
def sign_up_params
params.require(:user).permit(:first_name, :last_name, :email, :email_confirmation, :password, :remember_me)
[**my attempt:] params.permit(:user).permit(:profile_name)
end
end
Take a look at the Rails and Devise example application from the RailsApps project.
Here's how to add a name
attribute to the User model. If you don't include a validation validates_presence_of
in the model, it will be optional for the user.
First create the migration with a generator.
The migration:
# db/migrate/..._add_name_to_users.rb
class AddNameToUsers < ActiveRecord::Migration
def change
add_column :users, :name, :string
end
end
You need to override the Devise controller to handle strong parameters in Rails 4.0 (and newer).
The controller:
# app/controllers/registrations_controller.rb
class RegistrationsController < Devise::RegistrationsController
before_filter :update_sanitized_params, if: :devise_controller?
def update_sanitized_params
devise_parameter_sanitizer.for(:sign_up) {|u| u.permit(:name, :email, :password, :password_confirmation)}
devise_parameter_sanitizer.for(:account_update) {|u| u.permit(:name, :email, :password, :password_confirmation, :current_password)}
end
end
The form:
# app/views/devise/registrations/new.html.erb
<h2>Sign up</h2>
<%= form_for(resource, :as => resource_name, :url => registration_path(resource_name)) do |f| %>
<%= devise_error_messages! %>
<p><%= f.label :name %><br />
<%= f.text_field :name %></p>
<div><%= f.label :email %><br />
<%= f.email_field :email %></div>
<div><%= f.label :password %><br />
<%= f.password_field :password %></div>
<div><%= f.label :password_confirmation %><br />
<%= f.password_field :password_confirmation %></div>
<div><%= f.submit "Sign up" %></div>
<% end %>
<%= render "devise/shared/links" %>
Adjust the routes to accommodate the new controller.
The routes:
# config/routes.rb
RailsDevise::Application.routes.draw do
root :to => "home#index"
devise_for :users, :controllers => {:registrations => "registrations"}
resources :users
end
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.