0

Is there a way to display an error when a sent param is not in allowed list (in development)?

I very often forget to add the param to the list and don't notice it in the first place.

Joshua Muheim
  • 12,617
  • 9
  • 76
  • 152
  • This is pretty vague. At the very least, you ought to let us know what programming language you are talking about. Possibly also provide an example or two... – twalberg May 19 '14 at 20:29
  • I'm sorry, I though selecting the strong-parameters tag would have made it obvious I'm talking about Ruby on Rails. I added it as tag now. – Joshua Muheim May 19 '14 at 20:32

1 Answers1

1

I don't think StrongParameters does this already, but you're free to do it on your own. For example:

def object_params
  permitted_params = [:a, :b, :c]
  params.require(:some_object_name).permit(*permitted_params)
  if Rails.env.development? && permitted_params.exclude?(some_param)
    # TODO: Raise an exception or log an error or whatever you want to do here.
  end
end

UPDATE

I found out the strong_parameters gem (included by default in Rails 4) does allow for some flexibility here! See this section of the readme: https://github.com/rails/strong_parameters#handling-of-unpermitted-keys. So, in development environment the unpermitted keys should be logged already. And you can change that to do a raise instead if you want. Cool! If this isn't exactly what you want and the above code isn't either then you can probably monkey-patch or fork the gem to do something special with unpermitted keys across your entire app.

pdobb
  • 17,688
  • 5
  • 59
  • 74
  • I'm not sure whether I understand what you mean. I'd like to have a mechanism which prevents me from sending parameters that are not in the white list. So if I add a new attribute, then add a form input and send it, then a warning should appear on screen. – Joshua Muheim May 20 '14 at 11:22
  • Typically validations would take care of making sure all required attributes are properly filled out in the form. So if you haven't added an attribute to the list of permitted params and submit the form then the form submission would complain that nothing had been entered for that attribute (since it doesn't get set in the object if it isn't listed in the permitted attributes list). Does that help? – pdobb May 20 '14 at 12:50
  • Or if you don't want validations then you could use my above code sample to come up with a different way of displaying the error -- perhaps by setting `flash[:error]` and then, if a flash error is present, skip form validation or whatever you want to do to make sure the form submission fails. – pdobb May 20 '14 at 13:00