can
使用兩個參數:第一個是用戶正試圖對資源執行的動作的類型,第二個是資源(可以是類名或實例變量)本身。如果你有你的能力設置正確,你應該能夠做這樣的事情:
def show
if params[:format].eql?("pdf")
// do something
elsif params[:format].eql?("csv")
if can? :read, resource
#do stuff
end
end
end
不要忘記,你必須有你的用戶運行任何慘慘檢查之前進行身份驗證。 can?
方法只返回true或false。我通常喜歡使用authorize!
方法來檢查功能。不像can
,它會增加CanCan::AccessDenied
錯誤,你可以挽救和優雅地處理。行內的東西:
#models/ability.rb
class Ability
include CanCan::Ability
def initialize(user)
user ||= User.new # guest user (not logged in)
if user.role? :admin
can :manage, :all
elsif user.role? :hiring_manager
can [:read, :update], Post, user_id: user.id
end
end
end
#controllers/posts_controller.rb
class PostsController < ApplicationController::Base
before_filter :authenticate_user
def show
@post = Post.find(params[:id])
authorize! :read, @post # will thorow an exception if not allowed
end
end
然後,我只是在ApplicationController級別捕獲異常。
這應該被標記爲答案。謝謝! – 2013-05-15 17:20:17
完美 - 除了縮進4個空格:D – Hendrik 2017-01-19 13:50:01