2015-05-03 72 views
0

我有一個用戶和一個具有多對多關聯的組織模型,通過成員資格模型。用戶(沒有角色)應該只能創建,閱讀和更新他們作爲成員所屬的組織。帶有Rails和CanCanCan的授權和組

我在CanCanCan的Ability類中放入以下內容,並在組織模型上使用load_and_authorize_resource

can [:create, :read, :update], Organization do |organization| 
    !(organization.memberships & user.memberships).empty? 
end 

當我加載/組織(索引頁)時,@organizations爲零。

當我設置@organizations = Article.accessible_by(current_ability)我得到以下錯誤:

The accessible_by call cannot be used with a block 'can' definition. The SQL cannot be determined for :index Organization(id:integer...

docs提建議使用SQL,但我不太瞭解。

回答

0

看起來這條線是問題的一部分。

!(organization.memberships & user.memberships).empty? 

我去了下面的版本看起來更簡單和正確。

organization.memberships.pluck(:user_id).include?(user.id) 

誤差與塊調用accessible_by(current_ability)時仍然存在,但我可以用設計的current_user方法來解決辦法。