Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 429
Jason Waldrip Avatar asked Jan 09 '12 23:01

Jason Waldrip


2 Answers

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.

like image 163
Michelle Tilley Avatar answered Oct 13 '22 19:10

Michelle Tilley


For both scenarios, you'd pass it in the same way that you declare it originally. So for example:

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

If you did

user = User.new(:name => "John", :credit_card => "1234123412341234")

Then you won't be able to assign the credit_card:

user.attributes # {:name => "John", :credit_card => nil} 

However, if you state that it will be :as => :admin then it allows it

user = User.new({:name => "John", :credit_card => "1234123412341234"}, :as => :admin)
user.attributes # {:name => "John", :credit_card => "1234123412341234"} 

More information:

http://www.enlightsolutions.com/articles/whats-new-in-edge-scoped-mass-assignment-in-rails-3-1

like image 29
iwasrobbed Avatar answered Oct 13 '22 19:10

iwasrobbed