2

我在 Rails 应用程序中安装 cancan gem

而且我的ability.rb像这样受阻...

can [:action1,:action2,:action3] ,Obj do |x|
  # I wante to get current action, like this
  if action == action1
    #do something
  end
end

而且我不想在特殊块中分离每个动作

如何在能力块中获得当前动作?

4

2 回答 2

1

您可以使用 action 作为变量初始化 Ability 类实例方法:

#models/ability.rb

class Ability
  include CanCan::Ability

  def initialize(user, action)

    can action.to_sym, Obj do |x|
       #do something with your action (and user?)
    end

  end

end

现在您可以初始化将当前操作传递给它的新能力:

#application_controller.rb

def current_ability
  @current_ability ||= Ability.new(current_user, params[:action])
end

并使用存储在默认参数中的操作名称应用任何规则:action

于 2013-08-25T15:26:58.390 回答
0

正是我需要做的!我最终得到了这个解决方案:

[:action1, :action2].each do |action|
  can action, Obj do |x|
    puts "#{action}" # print the given action
  end
end
于 2020-12-28T16:55:37.257 回答