Question

I am migrating to Rails4, and I encounter some troubles with the new "strong parameters" feature.

In my UsersController, i have:

params.require(:user).permit(:email, :name, :password, :accept_mail_news)

But if somebody pass incorrect parameters, like

{"user"=>"a dummy string"}

Instead of receiving a 400, he will receive a 500:

#<NoMethodError: undefined method `permit' for "a dummy string":String>

Is there a generic way to "check types" in strong parameters, or must I do it all manually ?

Was it helpful?

Solution

One way I can think of is to check if params.require(:user) respond_to? permit method. Something like:

# app/controllers/users_controller.rb

def user_params
  if params.require(:user).respond_to?(:permit) 
    params.require(:user).permit(:email, :name, :password, :accept_mail_news)
  else
    # Raise error, notify users...
  end
end

try could also be an option using which would return nil if params.require(:user) does not respond to permit:

# app/controllers/users_controller.rb

def user_params
  params.require(:user).try(:permit, :email, :name, :password, :accept_mail_news)
end

OTHER TIPS

The structure of the parameters you receive is determined by the HTML that is running in the page at time of submission which in turn is determined by the view (and supporting code) you've implemented for your app. If you design your view properly, then the user value will always be a hash and you won't have the problem you describe.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top