在RoR中将Params传递给CanCan

我有一个像这样的方法的控制器;

def show if params[:format].eql?("pdf") // do something elsif params[:format].eql?("csv") // do something end end 

但我有不同角色的用户。 所以我使用CanCan来管理访问控制。 现在我想X角色可以在控制器中执行动作show iff params[:format].eql?("csv")

我觉得它可能会像; can :show, resource if params[:format].eql?("csv") 。 那么如何将参数发送到ability.rb?

任何的想法?

谢谢。

在ApplicationController中添加以下内容:

 # CanCan - pass params in to Ability # https://github.com/ryanb/cancan/issues/133 def current_ability @current_ability ||= Ability.new(current_user, params) end 

最新答案在CanCan wiki中: https : //github.com/ryanb/cancan/wiki/Accessing-Request-Data

can有两个参数:第一个是用户尝试对资源执行的操作类型,第二个是资源(可以是类名或实例变量)本身。 如果你的能力设置正确,你应该可以这样做:

 def show if params[:format].eql?("pdf") // do something elsif params[:format].eql?("csv") if can? :read, resource #do stuff end end end 

不要忘记在运行任何CanCan检查之前必须对用户进行身份validation。 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级别捕获exception。