6
votes

I'm using Rails 4.0.0 and Devise 3.0.2 and trying to configure Devise with Strong Parameters following this instruction within the Devise README.

I wrote code like this in the application_controller.rb

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

  protected

  def configure_permitted_parameters
    devise_parameter_sanitizer.for(:sign_up) << :nick
  end
end

Then I visited http://localhost:3000/users/sign_up. I got a NoMethodError in Devise::RegistrationsController#new, which says:

undefined method <<' for {}:ActionController::Parameters

and points to the exact line where I wrote devise_parameter_sanitizer.for(:sign_up) << :nick

Is there anything I did wrong? Thanks for your help.

3
I tried exactly the same code and get the same error. devise_parameter_sanitizer.for(:sign_up) returns an empty hash, so it's not possible to call << method on that. I've submitted [an issue][1], you can follow that. [1]: github.com/plataformatec/devise/issues/2574 - Rafał Cieślak
@RafałCieślak Thank you for your confirmation, I'll follow the issue. - Jun Zhou

3 Answers

5
votes

Try:

    class ApplicationController < ActionController::Base
      ...
      before_filter :configure_permitted_parameters, if: :devise_controller?   
      ...
      def configure_permitted_parameters
         devise_parameter_sanitizer.for(:sign_up) { |u| 
            u.permit(:email, :password, :password_confirmation, :nick) 
         }
      end

It works for me! :D

4
votes

As Jose Valim said, it's Devise 3.1.0.rc feature, that's why it doesn't work. You have to use other syntaxes that are in README.

4
votes

An issue exactly matches your problem : #2574 : devise_parameter_sanitizer.for(:sign_up) << :something raises an error.

In fact, the method to add custom fields to strong parameters like that is a new feature coming with Devise 3.1.

Since the current version in Rubygems.org is 3.0.3, you can't use this method in your rails project for now. You'll have to override the defaults like that :

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


But if you really need to, you can edit your Gemfile and replace this line

gem 'devise', '3.0.3'

with this one :

gem 'devise', github: 'plataformatec/devise', branch: 'master'

Then you can easily add your custom fields like that :

# Single field
devise_parameter_sanitizer.for(:account_update) << :first_name
# Multiple fields at a time
devise_parameter_sanitizer.for(:account_update) << [:first_name, :last_name]

But be warned, currently this is a Release Candidate : 3.1.0 RC1