Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
261 views
in Technique[技术] by (71.8m points)

Add Custom Field/Column to Devise with Rails 4

I'm attempting to add a full_name field/column to my User model (using the devise gem) and Rails 4.

Most of the examples online recommend using attr_accessible, but it sounds like this should be approached differently in Rails 4.

How would I add full_name to my User model? I've been able to successfully run the migration.

File: Migration > add_full_name_to_users

class AddFullNameToUsers < ActiveRecord::Migration
  def change
    add_column :users, :full_name, :string
  end
end

File: Registration > app/views/devise/registration/new.html

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

  <%= f.label :full_name %>
  <%= f.text_field :full_name, :autofocus => true %>

  <%= f.label :email %>
  <%= f.email_field :email %>
.
.
.
question from:https://stackoverflow.com/questions/16297797/add-custom-field-column-to-devise-with-rails-4

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Once your model has its full_name attribute, you will have to configure permitted parameters for the #sign_up and #account_update Devise actions.

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

  protected

  def configure_devise_permitted_parameters
    registration_params = [:full_name, :email, :password, :password_confirmation]

    if params[:action] == 'update'
      devise_parameter_sanitizer.for(:account_update) do 
        |u| u.permit(registration_params << :current_password)
      end
    elsif params[:action] == 'create'
      devise_parameter_sanitizer.for(:sign_up) do 
        |u| u.permit(registration_params) 
      end
    end
  end

end

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...