Question

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?

Was it helpful?

Solution

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

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top