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?
Strong Parameters, aka Strong Params, are used in many Rails applications to increase the security of data sent through forms. Strong Params allow developers to specify in the controller which parameters are accepted and used.
Method: ActionController::Parameters#fetchReturns a parameter for the given key .
Mass assignment is a feature of Rails which allows an application to create a record from the values of a hash. Example: User.new(params[:user]) Unfortunately, if there is a user field called admin which controls administrator access, now any user can make themselves an administrator with a query like.
Provides two methods for this purpose: require and permit . The former is used to mark parameters as required. The latter is used to set the parameter as permitted and limit which attributes should be allowed for mass updating.
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:
http://guides.rubyonrails.org/v3.2.13/active_record_validations_callbacks.html#performing-custom-validations
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With