Rails: Whitelist params


2018-06-02 · 1 min read

There is a gem called allowable which extends ActionController:Paramters with additional methods to whitelist or blacklist params values.

def model_params
  params.require(:model).permit(:status, :other_attribute)
    .allow(status: %w[pending accepted rejected])
end

The gem adds four methods to Hash: #allow, #allow!, #forbid and #forbid!.

hash = { one: 'one', two: 'two' }
 
hash.forbid(one: 'one') # => { two: 'two' }
hash.allow(one: 'two') # => { two: 'two' }
hash.allow(one: ['one', 'two']) # => { one: 'one', two: 'two' }
hash.forbid(one: ['one', 'two']) # => { two: 'two' }
hash.allow!(one: 'two') # => { two: 'two' }
hash.forbid!(two: 'two') # => {}

With String keys:

hash = { 'one' => 'one', 'two' => 'two' }
 
hash.forbid(one: 'one') # => { "one" => "one", "two" => "two" }
hash.forbid('one' => 'one') # => { "two" => "two" }