Reputation: 1380
Is it possible to mark a single attribute of a hash as required using strong parameters?
Given input like:
{
"example" => {
"optional": 1234,
"required": 5678
}
}
The standard strong params examples are:
params.require(:example).permit(:optional, :required)
Given that you can require certain parameters, I thought the following would work:
params.require(:example).require(:required)
params.require(:example).permit(:optional)
I've attempted:
params.require(:example => [ :required ]).permit(:optional)
params.require(:example).permit(:optional)
params[:example].require(:required)
And anything else I can think of.
Does anyone know if its possible?
Upvotes: 6
Views: 3899
Reputation: 16841
What you can do is use
def example_params
params.require(:example)
params[:example].require(:required)
params.require(:example).permit(:required, :optional)
end
The first line fails if :example
is missing. The second line fails if :required
is missing from :example
. The third line returns what you expect, while allowing :optional
.
Upvotes: 0
Reputation: 555
Greg!
I had the same question, but after all I found, that its not appropriate question.
Look, here is the source code of require method in strong_parameters
gem:
def require(key)
self[key].presence || raise(ActionController::ParameterMissing.new(key))
end
So, basically, there is no way to require "required" attribute in params hash. But look on it from different side. I think its better write your own require method in order to do that. Since I'm using rails, I just added validates_presence_of
to the model. If you want to make it dynamic, you may create custom validation. You can find its documentation here:
Upvotes: 5