Rails : Strong Params : Whilisting params : Implementation details

With strong parameters, Action Controller parameters are forbidden to be used in Active Model mass assignments until they have been whitelisted. This means that you’ll have to make a conscious decision about which attributes to allow for mass update. This is a better security practice to help prevent accidentally allowing users to update sensitive model attributes.

In addition, parameters can be marked as required and will flow through a predefined raise/rescue flow to end up as a 400 Bad Request.

param_hash = ActionController::Parameters.new({first_name: 'Shiva', last_name: 'Bhusal'})
=> {"first_name"=>"Shiva", "last_name"=>"Bhusal"}

# this is equivalent to 

param_hash = params

when I tried to use the Param to create a record for Lead model I got

my_lead = Lead.create param_hash
ActiveModel::ForbiddenAttributesError: ActiveModel::ForbiddenAttributesError
from /home/shiva/.rvm/gems/ruby-2.1.1/gems/activemodel-4.0.4/lib/active_model/forbidden_attributes_protection.rb:21:in `sanitize_for_mass_assignment'

However, we remember that the following codes are acceptable

 my_lead = Lead.create param_hash.to_h
 (1.4ms) BEGIN
 SQL (0.9ms) INSERT INTO `leads` (`created_at`, `first_name`, `last_name`, `updated_at`) VALUES ('2015-10-02 07:56:48', 'Shiva', 'Bhusal', '2015-10-02 07:56:48')
 (6.8ms) COMMIT

# This will not raise an ActiveModel::ForbiddenAttributes exception
# because ActiveRecord seems to permit assignment via hashes


my_lead = Lead.create(first_name: param_hash[:first_name], last_name: param_hash[:last_name])
 (0.5ms) BEGIN
 SQL (2.5ms) INSERT INTO `leads` (`created_at`, `first_name`, `last_name`, `updated_at`) VALUES ('2015-10-02 08:22:24', 'Shiva', 'Bhusal', '2015-10-02 08:22:24')
 (6.0ms) COMMIT

Now to add the params in ActionController::Parameters we did this and everything is okay

my_lead = Lead.create param_hash.permit(:first_name, :last_name) (0.6ms)
 SQL (0.5ms) INSERT INTO `leads` (`created_at`, `first_name`, `last_name`, `updated_at`) VALUES ('2015-10-02 08:26:00', 'Shiva', 'Bhusal', '2015-10-02 08:26:00')
 (4.9ms) COMMIT

What does the `permit` method do?

=> {"first_name"=>"Shiva", "last_name"=>"Bhusal"}
[16] pry(main)> after_permission = param_hash.permit(:last_name)
Unpermitted parameters: first_name
=> {"last_name"=>"Bhusal"}
[17] pry(main)> after_permission.class
=> ActionController::Parameters




Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s