访问模型属性的动态范围

发布于 2024-11-13 08:40:08 字数 468 浏览 1 评论 0原文

我目前正在使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

烟沫凡尘 2024-11-20 08:40:08

attr_accessible 用于过滤批量分配时传入的属性。这是一个方便的方法,这样开发人员就不需要手动清理传入的参数哈希,这是他无法控制的。

当显示信息时,开发人员可以完全控制他/她想要显示的内容,因此似乎没有理由限制读取功能。

但是,rails 允许您在查询中“选择”所需的属性:请参阅 http ://guides.rubyonrails.org/active_record_querying.html#selecting-specific-fields

您可以轻松创建一个名为 admin 的范围来限制所选值。

如果您不希望拥有完整的模型,而只想拥有值,则可以使用生成的 sql。例如。

ActiveRecord::Base.connection.select_values(Customer.select('name').to_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.

ActiveRecord::Base.connection.select_values(Customer.select('name').to_sql)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文