Flowdock
method

permit

Importance_3
v4.2.1 - Show latest stable - 0 notes - Class: Parameters
permit(*filters) public

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"}}
Show source
Register or log in to add new notes.