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.

有帮助吗?

解决方案

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.

其他提示

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

all the attributes you want to access as a specific user should be defined properly. For example:

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

This showed error for me. But when i modied it to

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

This worked fine when i used

    @user.update_attributes(params[:user], :as => :admin)
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top