Strong parameters require multiple

The solution proposed in Rails documentation (https://api.rubyonrails.org/classes/ActionController/Parameters.html#method-i-require) is:

def point_code
  params.require(:point_code).permit(:guid).tap do |point_code_params|
    point_code_params.require(:guid) # SAFER
  end
end

OK, ain't pretty but should do the trick. Assume you have params :foo, :bar and :baf you'd like to require all for a Thing. You could say

def thing_params
  [:foo, :bar, :baf].each_with_object(params) do |key, obj|
    obj.require(key)
  end
end

each_with_object returns obj, which is initialized to be params. Using the same params obj you require each of those keys in turn, and return finally the object. Not pretty, but works for me.


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


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