문제

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 ?

도움이 되었습니까?

해결책

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

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top