Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strong Parameters requiring an attribute

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?

like image 755
Greg Olsen Avatar asked Apr 26 '13 22:04

Greg Olsen


People also ask

What are strong parameters?

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.

What does params fetch do?

Method: ActionController::Parameters#fetchReturns a parameter for the given key .

What is mass assignment in Rails?

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.

What is permit in Ruby on Rails?

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.


1 Answers

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

like image 164
RunFor Avatar answered Oct 23 '22 03:10

RunFor