-
Notifications
You must be signed in to change notification settings - Fork 164
Require for nested parameters is broken #70
Comments
Looking at the code, require is best used to identify the root element, and permit to define the permissible children of that element. So for your example you would do:
or
|
Looking at this again, this should be a valid input:
As is evident from this test: action_controller_required_params_test.rb The problem is Parameters#require:
presence returns the value of self[key], so it is the child that is being passed along chain and not the root hash. Used this way require will do some unexpected things. For example:
That is, the object returned would be the value of the last required item. So a fix could be to rewrite Parameters#require, so that it returns the root hash (self), and accepts a syntax that allows you to identify which nested parameters are required. Permit already has much of that functionality. So you could code Parameters#require so that it goes through each element and raises an exception if it doesn't find them in the parent hash, and then passed them onto permit to do its magic. Then the syntax would become:
This would in effect run permit twice - the first time raising an exception if a parameter is missing. The second time just marking the fields as permitted. Note that params[:user] is called first, as require is no longer passing on a part of the root hash, but the root hash itself. |
There needs to be a way to make sure the nested model parameters are required and then permit those nested values. |
I'm finding myself in a similar situation. I need to require nested params and the current implementation doesn't provide that functionality. @reggieb The approach you proposed solves the issue and keeps the syntax clear. |
You may want to have a look at: |
No one has had a need for requiring nested parameters since 2013? |
Using current API, it's not really possible to do a sane check for a nested param. Consider the following check:
If you now supply
?user=test
as a param, the second require call will be sent to a string instance.This could be solved if require would support nested syntax, i.e.:
The above syntax would make code more readable for deeper nested params:
params.require(:user).require(:book).require(:authorization).require(:token)
becomesparams.require('user.book.authorization.token')
Any thoughts?
The text was updated successfully, but these errors were encountered: