Search code examples
ruby-on-railsruby-on-rails-3.1mass-assignmentattr-accessible

Using Rails 3.1 :as => :admin for updating attributes protected by attr_accessible


After reading about attr_accessible in the Rails 3.1 API, I see that there is an as :admin option in there. I would like to know two things.

  1. If the user has an admin flag, how do does my controller tell my model that the user is an admin.

  2. If the user is an owner, can i specify :as => owner in my model, and once again how does my controller inform my model they are the owner of an item.


Solution

  • There is no built-in integration with models; you pass in the role in the assign_attributes call:

    @project.assign_attributes(params[:project], :as => :admin)
    

    The :as parameter defaults to :default, and you can pass in any symbol that you want. To integrate this into your User model, you could give it an attribute called role, and then do something like:

    @project.assign_attributes(params[:project], :as => current_user.role.to_sym)
    

    You can also bypass the protection using :without_protection:

    @project.assign_attributes(params[:project], :without_protection => true)
    

    In a similar way, new, create, create!, update_attributes, and update_attributes! methods all respect mass-assignment security. The Ruby on Rails guide on security has more info.