2011-06-11 65 views
1

我爲我的訂購應用程序使用了Cancan,Devise,Rails 3。CanCan限制發現數據

每個用戶都有許多公司通過協議。每家公司也有許多用戶通過協議。

在我的能力模型中,我有以下幾點:

class Ability 
    include CanCan::Ability 

    def initialize(user) 
    user ||= User.new # guest user 
    if user.role? :super 
     can :manage, :all 
    elsif user.role? :admin 
     can :manage, [User, Company, Order] 
    elsif user.role? :tech 
     can :manage, [User, Company, Tech] 
    elsif user.role? :customer_admin 
     can [:read, :update], User, :id => user.id 
     can [:read, :update], Company, :id => user.id 
     can [:read ], Order, :id => user.id    
    end 
    end 
end 

當,我一直在試圖告訴他們只有他們正在與相關公司一customer_admin日誌。在公司的觀點中,我可以看到用戶列表就好。

在我公司的控制器(指數),我試着這樣做:

@usercompanies = Company.where(['user_id = ?', current_user.id ]) 

然而,這列出了錯誤的公司?

肯定這是一個愚蠢的新手錯誤,但會感謝您的幫助。如果你需要別的東西,讓我知道。

+0

此外,在我的回答中,您確實希望保留行'can [:read,:update],User,:id => user.id',因爲用戶模型的id和current_user id是相同的。所有其他記錄需要根據我的答案進行修改。 – 2011-06-11 14:39:54

回答

1

您可以快速添加cancan的限制條件,並且在第一次將其設置時也是令人費解的。用於設置的文檔是here。而且,正如你想使你的索引操作在你的控制器看起來像這樣的引用:

@usercompanies = Company.accessible_by(current_ability) 

然而,在創業板本應自動進行索引操作來完成的最新版本。我認爲你在abilities.rb中有一個錯誤,因爲當你有一條記錄並且你和一個用戶聯繫時,它通常會有一個名爲user_id的文件夾。你想使用像這樣:

can [:read ], Order, :user_id => user.id 

由於屬性id通常被用作記錄的唯一ID和association的不是ID。

+0

m謝謝!這非常方便。我不能讓它爲我的公司工作,因爲它們通過協議與許多用戶相關。我怎樣才能在我的能力中加上這個詞呢?我試過這個可以[:read,:update],Company,:user_id => user.id,但它再次列出錯誤的公司。 Jx – 2011-06-12 19:21:33

+0

如果您限制用戶看到他們已經進入的協議,那麼他們應該只能看到這種關係中的公司?也許更好的方法是使用像https://github.com/ryanb/cancan/wiki/Defining-Abilities-with-Blocks這樣的代碼塊,也許可以使用像'if user.agreements.includes?(agreement)'這樣的代碼。讓你檢查一下用戶是否可以訪問它。 – 2011-06-12 23:44:15

+0

好的,很酷。我會看一看。再次感謝 – 2011-06-13 17:17:35