Skip to content

Instantly share code, notes, and snippets.

@iagopiimenta
Created February 18, 2016 14:48
Show Gist options
  • Save iagopiimenta/43a66712c021a9d3f540 to your computer and use it in GitHub Desktop.
Save iagopiimenta/43a66712c021a9d3f540 to your computer and use it in GitHub Desktop.
Rails 4: Strong parameters: allow hashes
module ActionController
class Parameters
# See https://github.com/rails/rails/blob/v4.2.5.1/actionpack/lib/action_controller/metal/strong_parameters.rb#L562
def hash_filter(params, filter)
filter = filter.with_indifferent_access
# Slicing filters out non-declared keys.
slice(*filter.keys).each do |key, value|
next unless value
if filter[key] == EMPTY_ARRAY
# Declaration { comment_ids: [] }.
array_of_permitted_scalars_filter(params, key)
else
# Declaration { user: :name } or { user: [:name, :age, { address: ... }] }.
params[key] = each_element(value) do |element|
if element.is_a?(Hash)
element = self.class.new(element) unless element.respond_to?(:permit)
# Allow Hash
if [Hash, [Hash]].include?(filter[key])
element.permit(*Array.wrap(element.keys))
else
element.permit(*Array.wrap(filter[key]))
end
end
end
end
end
end
end
end
# https://github.com/rails/rails/blob/v4.2.5.1/actionpack/lib/action_controller/metal/strong_parameters.rb
params = ActionController::Parameters.new(
form: {
scalar: 'foobar',
many: [
{
field1: 'foo'
},
{
fiedl2: 'bar'
}
],
single: {
filed3: 'baz'
}
}
)
params.require(:form).permit(:scalar, many: Hash, single: Hash)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment