Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strong parameters require multiple

I'm receiving a JSON package like:

{   "point_code" : { "guid" : "f6a0805a-3404-403c-8af3-bfddf9d334f2" } } 

I would like to tell Rails that both point_code and guid are required, not just permitted.

This code seems to work but I don't think it's good practice since it returns a string, not the full object:

params.require(:point_code).require(:guid) 

Any ideas how I could do this?

like image 571
Rob Avatar asked Mar 18 '14 18:03

Rob


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 is params require in rails?

The require method ensures that a specific parameter is present, and if it's not provided, the require method throws an error. It returns an instance of ActionController::Parameters for the key passed into require . The permit method returns a copy of the parameters object, returning only the permitted keys and values.


2 Answers

I had a similar need and what I did was

def point_code_params   params.require(:point_code).require(:guid) # for check require params   params.require(:point_code).permit(:guid) # for using where hash needed end 

Example:

def create   @point_code = PointCode.new(point_code_params) end 
like image 67
sarunw Avatar answered Sep 20 '22 04:09

sarunw


As of 2015 (RoR 5.0+) you can pass in an array of keys to the require method in rails:

params.require([:point_code, :guid])

http://api.rubyonrails.org/classes/ActionController/Parameters.html#method-i-require

like image 36
raveren Avatar answered Sep 23 '22 04:09

raveren