简体   繁体   中英

Add new fields to Devise model. Rails 5

So I wanna add some new fields to my Devise model User. When I was using Rails 3 I just added new fields to model and added those fields to Model.rb

attr_accessible :name, :etc  

and then I changed Registration view. Now I've done the same, but I haven't Devise/User controller so I can't do something like this

 def user_params
      params.require(:users).permit(:name)
 end 

Or

attr_accessible :name, :etc 

Customizing the RegistrationsController

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

Now we need to tell Devise to use our registrations controller - we can do this in our config/routes.rb file.

devise_for :users, :controllers => { registrations: 'registrations' }

There are three parts to this:

  1. Generate the migration to the table to add the fields to your database schema.

rails generate migration add_name_to_users name:string

  1. You need to add the ability to add/edit the name in the registration/edit forms for your user. (which it seems like you've already done in your first code sample)

  2. You need to add the strong params that you added to your controller (which you've already done in your second code sample.

Basically it seems like you haven't generated the migration. Are you getting any error messages?

Since Devise 4, the Parameter Sanitaizer API has changed:

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

  protected

  def configure_permitted_parameters
    devise_parameter_sanitizer.permit(:sign_up, keys: [:username])
  end
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.

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