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?
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.
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.
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
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
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