Search code examples
ruby-on-railsrubyruby-on-rails-3strong-parameters

allow set_locale with strong_parameters gem & devise


I'm using strong parameters gem on small project with devise

I have added User.rb a locale column. This is my controllers/users/registrations_controller.rb file:

class Users::RegistrationsController < Devise::RegistrationsController
  def resource_params
    params.require(:user).permit(:username, :email, :password, :password_confirmation, :locale)
  end
  private :resource_params
  def create
   #add params[:locale] to resource.locale here
   super
  end
end

These are the parameters received from form:

Parameters: {"authenticity_token"=>"ZyrtToHcwsX3zl2ive93cpYaom6HNGA/jnYcSg7pQUQ=", "user"=>{"username"=>"[email protected]", "email"=>"[email protected]", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"}, "commit"=>"Create account", "locale"=>"es"}

I would like add to user :locale column the parameter params[:locale]

How can I do it?

Thanks!


Solution

  • I have fixed the problem overriding the create method from this doc:

    https://github.com/plataformatec/devise/blob/master/app/controllers/devise/registrations_controller.rb.

    If you want add specify column or field locale on your model user with strong parameters gem, you can add to controllers/users/registrations_controller.rb the next:

    class Users::RegistrationsController < Devise::RegistrationsController
    
      def create
        build_resource
        resource.locale = set_locale #set_locale or where you have stored your own locale
        if resource.save
          if resource.active_for_authentication?
            set_flash_message :notice, :signed_up if is_navigational_format?
            sign_up(resource_name, resource)
            respond_with resource, :location => after_sign_up_path_for(resource)
          else
            set_flash_message :notice, :"signed_up_but_#{resource.inactive_message}" if is_navigational_format?
            expire_session_data_after_sign_in!
            respond_with resource, :location => after_inactive_sign_up_path_for(resource)
          end
        else
          clean_up_passwords resource
          respond_with resource
        end
      end
    
      def resource_params
        params.require(:user).permit(:username, :email, :password, :password_confirmation, :locale)
      end
    
      private :resource_params
    end
    

    Regards!