问题描述
在阅读了有关Rails 3.1 API中的 attr_accessible ,我看到那里有一个as :admin
选项.我想知道两件事.
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.
-
如果用户具有admin标志,我的控制器如何告诉我的模型该用户是admin.
If the user has an admin flag, how do does my controller tell my model that the user is an admin.
如果用户是所有者,我可以在模型中指定:as => owner
,我的控制器又如何通知我的模型,他们是商品的所有者.
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.
推荐答案
模型之间没有内置的集成;您在assign_attributes
调用中传递了角色:
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)
:as
参数默认为:default
,您可以传入所需的任何符号.要将其集成到您的User
模型中,您可以为其提供一个名为role
的属性,然后执行以下操作:
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)
您还可以使用:without_protection
绕过保护:
You can also bypass the protection using :without_protection
:
@project.assign_attributes(params[:project], :without_protection => true)
以类似的方式,new
,create
,create!
,update_attributes
和update_attributes!
方法都遵循质量分配安全性. 关于安全性的Ruby on Rails指南具有更多信息.
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.
这篇关于使用Rails 3.1:as => :admin用于更新受attr_accessible保护的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!