2013-03-14 24 views
0

我有一個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類只是沒有顯示價格?

+0

你不能做到這一點使用康康舞 – jvnill 2013-03-14 11:52:56

+0

所以,我該怎麼辦呢? – marcamillion 2013-03-14 12:35:52

回答

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 %> 
+0

非常奇怪的是,我得到這個錯誤:'NoMethodError at/ 未定義的方法'價格'爲#'at line'不能:read,[Product.price]'。 – marcamillion 2013-03-14 13:47:08

+0

啊對不起,我複製了你的代碼,但忘了刪除那一行。更新我的回答 – jvnill 2013-03-14 13:53:08

+0

完美....這工作。任何想法在這:http://stackoverflow.com/questions/15407491/how-do-i-restrict-the-currently-logged-in-user-to-only-see-products-that-belong? – marcamillion 2013-03-14 22:49:33

相關問題