Search code examples
ruby-on-rails-3mass-assignment

how to protect attributes from mass assignement


Hi I have a NOOB question in light of what happend at GITHUB with their application being exploited because of the security hole in Rails.

What is the best way to protect object attributes in Rails but still allow them to be assigned values where applicable?

Thanks


Solution

  • Actually Rails 3.1 has added new built-in ways to handle mass-assignment with roles which is probably something that you want to take a look at.

    Release notes here

    Basically it works like this:

    class User < ActiveRecord::Base
      attr_accessible :name
      attr_accessible :name, :role, :as => :admin
    end
    

    What this enables you to do is that you can use the following way to allow the user to update his own information in one of your controllers:

    @user.update_attributes(params[:user])
    

    And that usage can never update the :role attribute in the User model. But when you have your admin users managing the roles in a separate controller, then you can user the following syntax:

    @user.update_attributes(params[:user], :as => :admin)
    

    And that will allow the :role attribute to be updated as well