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

懵懂的女人 提交于 2019-12-18 19:37:14

问题


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.


回答1:


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.




回答2:


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




回答3:


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)


来源:https://stackoverflow.com/questions/8796827/using-rails-3-1-as-admin-for-updating-attributes-protected-by-attr-accessib

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!