Returns a new ActionController::Parameters
instance that
includes only the given filters
and sets the
permitted
attribute for the object to true
. This
is useful for limiting which attributes should be allowed for mass
updating.
params = ActionController::Parameters.new(user: { name: 'Francesco', age: 22, role: 'admin' }) permitted = params.require(:user).permit(:name, :age) permitted.permitted? # => true permitted.has_key?(:name) # => true permitted.has_key?(:age) # => true permitted.has_key?(:role) # => false
Only permitted scalars pass the filter. For example, given
params.permit(:name)
:name
passes it is a key of params
whose
associated value is of type String
, Symbol
,
NilClass
, Numeric
, TrueClass
,
FalseClass
, Date
, Time
,
DateTime
, StringIO
, IO
,
ActionDispatch::Http::UploadedFile
or
Rack::Test::UploadedFile
. Otherwise, the key
:name
is filtered out.
You may declare that the parameter should be an array of permitted scalars by mapping it to an empty array:
params = ActionController::Parameters.new(tags: ['rails', 'parameters']) params.permit(tags: [])
You can also use permit
on nested parameters, like:
params = ActionController::Parameters.new({ person: { name: 'Francesco', age: 22, pets: [{ name: 'Purplish', category: 'dogs' }] } }) permitted = params.permit(person: [ :name, { pets: :name } ]) permitted.permitted? # => true permitted[:person][:name] # => "Francesco" permitted[:person][:age] # => nil permitted[:person][:pets][0][:name] # => "Purplish" permitted[:person][:pets][0][:category] # => nil
Note that if you use permit
in a key that points to a hash, it
won't allow all the hash. You also need to specify which attributes
inside the hash should be whitelisted.
params = ActionController::Parameters.new({ person: { contact: { email: 'none@test.com', phone: '555-1234' } } }) params.require(:person).permit(:contact) # => {} params.require(:person).permit(contact: :phone) # => {"contact"=>{"phone"=>"555-1234"}} params.require(:person).permit(contact: [ :email, :phone ]) # => {"contact"=>{"email"=>"none@test.com", "phone"=>"555-1234"}}
Please login to continue.