class ActionController::Parameters
params # => “value”<br>params # => “value”
params = ActionController::Parameters.new(key: ‘value’):key or "key".
You can fetch values of ActionController::Parameters using either
runtime.
environment they should only be set once at boot-time and never mutated at
Please note that these options *are not thread-safe*. In a multi-threaded
# => ActionController::UnpermittedParameters: found unpermitted keys: a, b
params.permit(:c)
params = ActionController::Parameters.new(a: “123”, b: “456”)
ActionController::Parameters.action_on_unpermitted_parameters = :raise
# => {}
params.permit(:c)
params = ActionController::Parameters.new(a: “123”, b: “456”)
params.permitted? # => true
params = ActionController::Parameters.new
ActionController::Parameters.permit_all_parameters = true
params.permitted? # => false
params = ActionController::Parameters.new
Examples:
in test and development environments, false otherwise.
ActionController::UnpermittedParameters exception. The default value is :log
write a message on the logger or :raise to raise
that are not explicitly permitted are found. The values can be :log to
* action_on_unpermitted_parameters - Allow to control the behavior when parameters
permitted by default. The default is false.
* permit_all_parameters - If it’s true, all the parameters will be
It provides two options that controls the top-level behavior of new instances:
# => #<Person id: 1, name: “Francesco”, age: 22, role: “user”>
Person.first.update!(permitted)
permitted.permitted? # => true
permitted.class # => ActionController::Parameters
permitted # => {“name”=>“Francesco”, “age”=>22}
permitted = params.require(:person).permit(:name, :age)
})
}
role: ‘admin’
age: 22,
name: ‘Francesco’,
person: {
params = ActionController::Parameters.new({
as permitted and limit which attributes should be allowed for mass updating.
used to mark parameters as required. The latter is used to set the parameter
Provides two methods for this purpose: #require and #permit. The former is
and thus prevent accidentally exposing that which shouldn’t be exposed.
Allows you to choose which attributes should be whitelisted for mass updating
== Action Controller Parameters
def ==(other)
Returns true if another +Parameters+ object contains the same content and
def ==(other) if other.respond_to?(:permitted?) self.permitted? == other.permitted? && self.parameters == other.parameters elsif other.is_a?(Hash) ActiveSupport::Deprecation.warn <<-WARNING.squish Comparing equality between `ActionController::Parameters` and a `Hash` is deprecated and will be removed in Rails 5.1. Please only do comparisons between instances of `ActionController::Parameters`. If you need to compare to a hash, first convert it using `ActionController::Parameters#new`. WARNING @parameters == other.with_indifferent_access else @parameters == other end end
def [](key)
params[:person] # => {"name"=>"Francesco"}
params = ActionController::Parameters.new(person: { name: 'Francesco' })
returns +nil+.
Returns a parameter for the given +key+. If not found,
def [](key) convert_hashes_to_parameters(key, @parameters[key]) end
def []=(key, value)
Assigns a value to a given +key+. The given key may still get filtered out
def []=(key, value) @parameters[key] = value end
def array_of_permitted_scalars?(value)
def array_of_permitted_scalars?(value) if value.is_a?(Array) && value.all? {|element| permitted_scalar?(element)} yield value end end
def convert_hashes_to_parameters(key, value)
def convert_hashes_to_parameters(key, value) converted = convert_value_to_parameters(value) @parameters[key] = converted unless converted.equal?(value) converted end
def convert_parameters_to_hashes(value, using)
def convert_parameters_to_hashes(value, using) case value when Array value.map { |v| convert_parameters_to_hashes(v, using) } when Hash value.transform_values do |v| convert_parameters_to_hashes(v, using) end.with_indifferent_access when Parameters value.send(using) else value end end
def convert_value_to_parameters(value)
def convert_value_to_parameters(value) case value when Array return value if converted_arrays.member?(value) converted = value.map { |_| convert_value_to_parameters(_) } converted_arrays << converted converted when Hash self.class.new(value) else value end end
def converted_arrays
loop that converts values. Also, we are not going to build a new array
Testing membership still loops, but it's going to be faster than our own
method to instantiate it only if needed.
looping in the common use case permit + mass-assignment. Defined in a
Attribute that keeps track of converted arrays, if any, to avoid double
def converted_arrays @converted_arrays ||= Set.new end
def delete(key)
optional code block is given and the key is not found, pass in the key
to key. If the key is not found, returns the default value. If the
Deletes and returns a key-value pair from +Parameters+ whose key is equal
def delete(key) convert_value_to_parameters(@parameters.delete(key)) end
def dig(*keys)
params2 = ActionController::Parameters.new(foo: [10, 11, 12])
params.dig(:foo, :zot, :xyz) # => nil
params.dig(:foo, :bar, :baz) # => 1
params = ActionController::Parameters.new(foo: { bar: { baz: 1 } })
at each step. Returns +nil+ if any intermediate step is +nil+.
Extracts the nested parameter from the given +keys+ by calling +dig+
def dig(*keys) convert_value_to_parameters(@parameters.dig(*keys)) end
def dup
copy_params = params.dup # => {"a"=>1}
params.permitted? # => true
params.permit!
params = ActionController::Parameters.new(a: 1)
instance. +permitted+ state is kept on the duped object.
Returns an exact copy of the ActionController::Parameters
def dup super.tap do |duplicate| duplicate.permitted = @permitted end end
def each_element(object)
def each_element(object) case object when Array object.grep(Parameters).map { |el| yield el }.compact when Parameters if object.fields_for_style? hash = object.class.new object.each { |k,v| hash[k] = yield v } hash else yield object end end end
def each_pair(&block)
Convert all hashes in values into parameters, then yield each pair in
def each_pair(&block) @parameters.each_pair do |key, value| yield key, convert_hashes_to_parameters(key, value) end end
def except(*keys)
params.except(:a, :b) # => {"c"=>3}
params = ActionController::Parameters.new(a: 1, b: 2, c: 3)
filters out the given +keys+.
Returns a new ActionController::Parameters instance that
def except(*keys) new_instance_with_inherited_permitted_status(@parameters.except(*keys)) end
def extract!(*keys)
params.extract!(:a, :b) # => {"a"=>1, "b"=>2}
params = ActionController::Parameters.new(a: 1, b: 2, c: 3)
Removes and returns the key/value pairs matching the given keys.
def extract!(*keys) new_instance_with_inherited_permitted_status(@parameters.extract!(*keys)) end
def fetch(key, *args)
params.fetch(:none, 'Francesco') # => "Francesco"
params.fetch(:none) # => ActionController::ParameterMissing: param is missing or the value is empty: none
params.fetch(:person) # => {"name"=>"Francesco"}
params = ActionController::Parameters.new(person: { name: 'Francesco' })
is given, then that will be run and its result returned.
if more arguments are given, then that will be returned; if a block
it will raise an ActionController::ParameterMissing error;
can't be found, there are several options: With no other arguments,
Returns a parameter for the given +key+. If the +key+
def fetch(key, *args) convert_value_to_parameters( @parameters.fetch(key) { if block_given? yield else args.fetch(0) { raise ActionController::ParameterMissing.new(key) } end } ) end
def fields_for_style?
def fields_for_style? @parameters.all? { |k, v| k =~ /\A-?\d+\z/ && (v.is_a?(Hash) || v.is_a?(Parameters)) } end
def hash_filter(params, filter)
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 next unless has_key? key if filter[key] == EMPTY_ARRAY # Declaration { comment_ids: [] }. array_of_permitted_scalars?(self[key]) do |val| params[key] = val end elsif non_scalar?(value) # Declaration { user: :name } or { user: [:name, :age, { address: ... }] }. params[key] = each_element(value) do |element| element.permit(*Array.wrap(filter[key])) end end end end
def initialize(parameters = {})
params.permitted? # => true
params = ActionController::Parameters.new(name: 'Francesco')
ActionController::Parameters.permit_all_parameters = true
Person.new(params) # => ActiveModel::ForbiddenAttributesError
params.permitted? # => false
params = ActionController::Parameters.new(name: 'Francesco')
end
class Person < ActiveRecord::Base
ActionController::Parameters.permit_all_parameters.
Also, sets the +permitted+ attribute to the default value of
Returns a new instance of ActionController::Parameters.
def initialize(parameters = {}) @parameters = parameters.with_indifferent_access @permitted = self.class.permit_all_parameters end
def inspect
def inspect "<#{self.class} #{@parameters} permitted: #{@permitted}>" end
def merge(other_hash)
Returns a new ActionController::Parameters with all keys from
def merge(other_hash) new_instance_with_inherited_permitted_status( @parameters.merge(other_hash) ) end
def method_missing(method_sym, *args, &block)
def method_missing(method_sym, *args, &block) if @parameters.respond_to?(method_sym) message = <<-DEPRECATE.squish Method #{method_sym} is deprecated and will be removed in Rails 5.1, as `ActionController::Parameters` no longer inherits from hash. Using this deprecated behavior exposes potential security problems. If you continue to use this method you may be creating a security vulnerability in your app that can be exploited. Instead, consider using one of these documented methods which are not deprecated: http://api.rubyonrails.org/v#{ActionPack.version}/classes/ActionController/Parameters.html DEPRECATE ActiveSupport::Deprecation.warn(message) @parameters.public_send(method_sym, *args, &block) else super end end
def new_instance_with_inherited_permitted_status(hash)
def new_instance_with_inherited_permitted_status(hash) self.class.new(hash).tap do |new_instance| new_instance.permitted = @permitted end end
def non_scalar?(value)
def non_scalar?(value) value.is_a?(Array) || value.is_a?(Parameters) end
def permit(*filters)
params.require(:person).permit(contact: [ :email, :phone ])
# => {"contact"=>{"phone"=>"555-1234"}}
params.require(:person).permit(contact: :phone)
# => {}
params.require(:person).permit(:contact)
})
}
}
phone: '555-1234'
email: 'none@test.com',
contact: {
person: {
params = ActionController::Parameters.new({
attributes inside the hash should be whitelisted.
it won't allow all the hash. You also need to specify which
Note that if you use +permit+ in a key that points to a hash,
permitted[:person][:pets][0][:category] # => nil
permitted[:person][:pets][0][:name] # => "Purplish"
permitted[:person][:age] # => nil
permitted[:person][:name] # => "Francesco"
permitted.permitted? # => true
permitted = params.permit(person: [ :name, { pets: :name } ])
})
}
}]
category: 'dogs'
name: 'Purplish',
pets: [{
age: 22,
name: 'Francesco',
person: {
params = ActionController::Parameters.new({
You can also use +permit+ on nested parameters, like:
params.permit(tags: [])
params = ActionController::Parameters.new(tags: ['rails', 'parameters'])
by mapping it to an empty array:
You may declare that the parameter should be an array of permitted scalars
Otherwise, the key +:name+ is filtered out.
+ActionDispatch::Http::UploadedFile+ or +Rack::Test::UploadedFile+.
+Date+, +Time+, +DateTime+, +StringIO+, +IO+,
+String+, +Symbol+, +NilClass+, +Numeric+, +TrueClass+, +FalseClass+,
+:name+ passes if it is a key of +params+ whose associated value is of type
params.permit(:name)
Only permitted scalars pass the filter. For example, given
permitted.has_key?(:role) # => false
permitted.has_key?(:age) # => true
permitted.has_key?(:name) # => true
permitted.permitted? # => true
permitted = params.require(:user).permit(:name, :age)
params = ActionController::Parameters.new(user: { name: 'Francesco', age: 22, role: 'admin' })
should be allowed for mass updating.
for the object to +true+. This is useful for limiting which attributes
includes only the given +filters+ and sets the +permitted+ attribute
Returns a new ActionController::Parameters instance that
def permit(*filters) params = self.class.new filters.flatten.each do |filter| case filter when Symbol, String permitted_scalar_filter(params, filter) when Hash then hash_filter(params, filter) end end unpermitted_parameters!(params) if self.class.action_on_unpermitted_parameters params.permit! end
def permit!
params.permitted? # => true
params.permit!
Person.new(params) # => ActiveModel::ForbiddenAttributesError
params.permitted? # => false
params = ActionController::Parameters.new(name: 'Francesco')
end
class Person < ActiveRecord::Base
mass assignment. Returns +self+.
Sets the +permitted+ attribute to +true+. This can be used to pass
def permit! each_pair do |key, value| Array.wrap(value).each do |v| v.permit! if v.respond_to? :permit! end end @permitted = true self end
def permitted=(new_permitted)
def permitted=(new_permitted) @permitted = new_permitted end
def permitted?
params.permit!
params.permitted? # => false
params = ActionController::Parameters.new
Returns +true+ if the parameter is permitted, +false+ otherwise.
def permitted? @permitted end
def permitted_scalar?(value)
def permitted_scalar?(value) PERMITTED_SCALAR_TYPES.any? {|type| value.is_a?(type)} end
def permitted_scalar_filter(params, key)
def permitted_scalar_filter(params, key) if has_key?(key) && permitted_scalar?(self[key]) params[key] = self[key] end keys.grep(/\A#{Regexp.escape(key)}\(\d+[if]?\)\z/) do |k| if permitted_scalar?(self[k]) params[k] = self[k] end end end
def reject(&block)
Returns a new instance of ActionController::Parameters with items
def reject(&block) new_instance_with_inherited_permitted_status(@parameters.reject(&block)) end
def reject!(&block)
def reject!(&block) @parameters.reject!(&block) self end
def require(key)
end
end
person_params.require(:name) # SAFER
params.require(:person).permit(:name).tap do |person_params|
def person_params
but take into account that at some point those ones have to be permitted:
name = params.require(:person).require(:name) # CAREFUL
params = ActionController::Parameters.new(person: { name: 'Finn' })
# CAREFUL
Technically this method can be used to fetch terminal values:
# ActionController::ParameterMissing: param is missing or the value is empty: user
user_params, profile_params = params.require(:user, :profile)
params = ActionController::Parameters.new(user: {}, profile: {})
Otherwise, the method re-raises the first exception found:
user_params, profile_params = params.require(:user, :profile)
params = ActionController::Parameters.new(user: { ... }, profile: { ... })
returned:
in order. If it succeeds, an array with the respective return values is
When given an array of keys, the method tries to require each one of them
# ActionController::ParameterMissing: param is missing or the value is empty: person
ActionController::Parameters.new(person: {}).require(:person)
# ActionController::ParameterMissing: param is missing or the value is empty: person
ActionController::Parameters.new(person: "\t").require(:person)
# ActionController::ParameterMissing: param is missing or the value is empty: person
ActionController::Parameters.new(person: nil).require(:person)
# ActionController::ParameterMissing: param is missing or the value is empty: person
ActionController::Parameters.new.require(:person)
Otherwise raises ActionController::ParameterMissing:
# => {"name"=>"Francesco"}
ActionController::Parameters.new(person: { name: 'Francesco' }).require(:person)
either present or the singleton +false+, returns said value:
When passed a single key, if it exists and its associated value is
This method accepts both a single key and an array of keys.
def require(key) return key.map { |k| require(k) } if key.is_a?(Array) value = self[key] if value.present? || value == false value else raise ParameterMissing.new(key) end end
def select(&block)
Returns a new instance of ActionController::Parameters with only
def select(&block) new_instance_with_inherited_permitted_status(@parameters.select(&block)) end
def select!(&block)
def select!(&block) @parameters.select!(&block) self end
def slice(*keys)
params.slice(:a, :b) # => {"a"=>1, "b"=>2}
params = ActionController::Parameters.new(a: 1, b: 2, c: 3)
don't exist, returns an empty hash.
includes only the given +keys+. If the given +keys+
Returns a new ActionController::Parameters instance that
def slice(*keys) new_instance_with_inherited_permitted_status(@parameters.slice(*keys)) end
def slice!(*keys)
Returns current ActionController::Parameters instance which
def slice!(*keys) @parameters.slice!(*keys) self end
def stringify_keys # :nodoc:
matter as we are using +HashWithIndifferentAccess+ internally.
pass +Parameters+ to a mass assignment methods in a model. It should not
This is required by ActiveModel attribute assignment, so that user can
def stringify_keys # :nodoc: dup end
def to_h
safe_params = params.permit(:name)
params.to_h # => {}
})
oddity: 'Heavy stone crab'
name: 'Senjougahara Hitagi',
params = ActionController::Parameters.new({
representation of this parameter with all unpermitted keys removed.
Returns a safe ActiveSupport::HashWithIndifferentAccess
def to_h if permitted? convert_parameters_to_hashes(@parameters, :to_h) else slice(*self.class.always_permitted_parameters).permit!.to_h end end
def to_unsafe_h
params.to_unsafe_h
})
oddity: 'Heavy stone crab'
name: 'Senjougahara Hitagi',
params = ActionController::Parameters.new({
parameter.
ActiveSupport::HashWithIndifferentAccess representation of this
Returns an unsafe, unfiltered
def to_unsafe_h convert_parameters_to_hashes(@parameters, :to_unsafe_h) end
def transform_keys(&block)
Returns a new ActionController::Parameters instance with the
def transform_keys(&block) if block new_instance_with_inherited_permitted_status( @parameters.transform_keys(&block) ) else @parameters.transform_keys end end
def transform_keys!(&block)
Performs keys transformation and returns the altered
def transform_keys!(&block) @parameters.transform_keys!(&block) self end
def transform_values(&block)
params.transform_values { |x| x * 2 }
params = ActionController::Parameters.new(a: 1, b: 2, c: 3)
running +block+ once for every value. The keys are unchanged.
Returns a new ActionController::Parameters with the results of
def transform_values(&block) if block new_instance_with_inherited_permitted_status( @parameters.transform_values(&block) ) else @parameters.transform_values end end
def transform_values!(&block)
Performs values transformation and returns the altered
def transform_values!(&block) @parameters.transform_values!(&block) self end
def unpermitted_keys(params)
def unpermitted_keys(params) self.keys - params.keys - self.always_permitted_parameters end
def unpermitted_parameters!(params)
def unpermitted_parameters!(params) unpermitted_keys = unpermitted_keys(params) if unpermitted_keys.any? case self.class.action_on_unpermitted_parameters when :log name = "unpermitted_parameters.action_controller" ActiveSupport::Notifications.instrument(name, keys: unpermitted_keys) when :raise raise ActionController::UnpermittedParameters.new(unpermitted_keys) end end end
def values_at(*keys)
Returns values that were assigned to the given +keys+. Note that all the
def values_at(*keys) convert_value_to_parameters(@parameters.values_at(*keys)) end