Вопрос

I have a Product model, and if a user is either logged in as a guest role, or not logged in, I don't want them to be able to see the prices on the products in my app.

I am using Devise, CanCan and Rolify.

I tried this, in my 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

But that doesn't seem to work. I haven't added any code to my views - do I need to do that, or should this ability class just not show the prices at all?

Это было полезно?

Решение

I'm taking back what I said. You can somehow do this using CanCan but it seems like a stretch. Can you try the following?

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

Then in your view, you have to manually check if the user can view prices

<% if can? :view_prices, Product %>
  <%= product.price %>
<% end %>
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top