Search code examples
ruby-on-railssecurityruby-on-rails-4mass-assignment

Mass Assignment Vulnerability


I have a model A such as :

class A < ActiveRecord::Base
  validates_uniqueness_of :name
  attr_accessible :name
end

I want to remove mass assignment vulnerability on attribute :name. So I deleted the line attr_accessible :name from this model. This model has no controller, so I didn't write any strong parameters. This model is used in a helper B.rb as follows :

num_users = A.where(:name => "NEW").count

Do I need to change this line in any way or will this line still work after I have deleted attr_attributed :name from my model?


Solution

  • First and foremost, this line num_users = A.where(:name => "NEW").count works fine with or without using mass-assignment. This is because where method do not assign data to a model record.

    On the other hand, it is rare to see a question with ruby-on-rails-4 and mass-assignment tags (there are only 7 with both).

    This is because Rails 4 remove mass_assignment and replace it with strong_parameters, you can find it at rails guides upgrade to 4.0.

    If the line attr_accessible :name is working fine on your rails 4 app. Then you must have the protected_attributes gem at your Gemfile.

    There must be a good reason for add the protected_attributes gem to a Rails 4 app. If not, you can remove from the Gemfile do bundle install and remove all the attr_accessible ... lines from your model. And also remove the :without_protection => true parameter from the model's actions (new, create, create!, update_attributes and update_attributes!, assign_attributes).

    If you keep the gem protected_attributes at the Gemfile. Then when you need to update some field which is not attr_accessible you must add a parameter without_protection: true to the action. This way:

    A.create({name: 'NEW'}, without_protection: true)
    

    And the record will be stored at the db. Otherwise it will not work.