2016-09-15 23 views
1

我在做一個rails項目,我試圖實現CanCanCan。我安裝了寶石並運行了命令。在我的項目CanCanCan不會停止正在編輯的帖子

class Ability 
    include CanCan::Ability 

    def initialize(user) 
    # Define abilities for the passed in user here. For example: 

     user ||= User.new # guest user (not logged in) 
     if user.admin? 
     can :manage, :all 
     else 
     can :update, Post do |post| 
      post.user == user 
     end 
     can :destroy, Post do |post| 
      post.user == user 
     end 
     can :create, Post 
     can :read, :all 
     end 

    end 
end 

不過,現在,如果我登錄到不同的用戶,我仍然可以編輯其他用戶的帖子:然後我說這ability.rb

任何與我失蹤的幫助將不勝感激。

回答

1

看到的錯誤是由添加load_and_authorize_resource我posts_controller

+0

很高興聽到它......然後,您應該將問題標記爲回答其他SO用戶的利益 – Ren

0

根據CanCanCan文檔,

塊時實際的實例對象的存在時才計算。 檢查課程權限時未對其進行評估(例如在 索引操作中)。這意味着對象屬性上不依賴 的任何條件都應該移出塊。

不這樣做

can :update, Project do |project| 
    user.admin? # this won't always get called 
end 

做到這一點

can :update, Project if user.admin? 

所以不是

can :update, Post do |post| 
    post.user == user 
end 
can :destroy, Post do |post| 
    post.user == user 
end 

更改那些

can :update, Post if post.user == user 
can :destroy, Post if post.user == user 
+0

您好,我想你的建議,它似乎沒有編輯其他用戶的帖子 – user2320239

0

我有它設置的方式nersoh一樣解決,該方法適用於我。你有沒有嘗試授權控制器中的Posts資源?例如,

class PostsController < ActionController::Base 
    load_and_authorize_resource 
end