访问模型属性的动态范围
我目前正在使用 Rails 3 中内置的批量分配安全性来确定哪些级别的用户可以更新其模型。例如,这段代码允许我根据用户级别保护属性。
class Customer
attr_accessor :name, :credit_rating
attr_accessible :name
attr_accessible :name, :credit_rating, :as => :admin
end
我希望能够对查找时出现的属性使用相同的想法。例如,我希望能够说出
Customer.all.as(:admin)
并取回信用评级。将此与执行
Customer.all
并取回除credit_ rating之外的所有属性
进行比较,这是rails支持但我错过的东西吗?
I'm currently using the mass assignment security baked into rails 3 to scope what level of users can update about their model. For example this code allows me to protect attributes based on the user level.
class Customer
attr_accessor :name, :credit_rating
attr_accessible :name
attr_accessible :name, :credit_rating, :as => :admin
end
I would like to be able to use this same idea for which attributes appear when I do a find. For example I would like to be able to say
Customer.all.as(:admin)
and get back the credit rating. Compare this to doing
Customer.all
and getting back all the attributes except the credit_rating
Is this something rails supports and I've missed?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
attr_accessible 用于过滤批量分配时传入的属性。这是一个方便的方法,这样开发人员就不需要手动清理传入的参数哈希,这是他无法控制的。
当显示信息时,开发人员可以完全控制他/她想要显示的内容,因此似乎没有理由限制读取功能。
但是,rails 允许您在查询中“选择”所需的属性:请参阅 http ://guides.rubyonrails.org/active_record_querying.html#selecting-specific-fields
您可以轻松创建一个名为 admin 的范围来限制所选值。
如果您不希望拥有完整的模型,而只想拥有值,则可以使用生成的 sql。例如。
attr_accessible is used to filter incoming attributes on mass assignment. This is a convenience method created so that a developer does not need to manually clean the incoming hash of params, something he does not control.
When displaying information a developer is in full control of what he/she desires to show, so there seems to be no reason to limit the read functionality.
However, rails allows you to "select" the attributes you desire in a query: see http://guides.rubyonrails.org/active_record_querying.html#selecting-specific-fields
You could easily create a scope with the name admin that would limit the selected values.
If you do not desire to have the full models, but only the values, you could use the generated sql. e:g.