【问题标题】:How do I restrict a role from not seeing prices on Products?如何限制角色看不到产品的价格?
【发布时间】:2013-03-14 11:01:38
【问题描述】:

我有一个Product 模型,如果用户以guest 角色登录或未登录,我不希望他们能够在我的应用中看到产品的价格.

我正在使用 Devise、CanCan 和 Rolify。

我试过这个,在我的ability.rb:

user ||= User.new # guest user (not logged in)
if user.has_role? :guest
  can :read, [Product, Vendor, Banner]
  cannot :read, [Product.price]      
end

但这似乎不起作用。我没有在我的视图中添加任何代码 - 我需要这样做吗,还是这个 ability 类根本不显示价格?

【问题讨论】:

  • 你不能用 cancan 做到这一点

标签: ruby-on-rails ruby-on-rails-3 authorization cancan rolify


【解决方案1】:

我收回我说过的话。您可以使用 CanCan 以某种方式做到这一点,但这似乎有点牵强。 您可以尝试以下方法吗?

if user.has_role? :guest
  can :read, [Product, Vendor, Banner]
  cannot :view_prices, Product
end

那么在你的视图中,你必须手动检查用户是否可以查看价格

<% if can? :view_prices, Product %>
  <%= product.price %>
<% end %>

【讨论】:

  • 奇怪的是,我得到了这个错误:NoMethodError at / undefined method 'price' for #&lt;Class:0x007feb523fe518&gt; at line cannot :read, [Product.price]
  • 啊抱歉,我复制了您的代码但忘记删除该行。更新了我的答案
  • 完美....这行得通。对此有何想法:stackoverflow.com/questions/15407491/…?
猜你喜欢
  • 2021-05-10
  • 1970-01-01
  • 2018-02-14
  • 2019-03-23
  • 1970-01-01
  • 2021-08-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多