使用cancan在rails中授权控制器操作

时间:2015-03-10 18:09:50

标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-4 cancan

我在控制器中有一些操作,并授权进行3次操作,

class TestController
 def test1
   authorize! :view, :testcase1
   #do things1
 end

 def test2
   authorize! :view, :testcase2
   #do things2
 end

 def test3
   authorize! :view, :testcase3
   #do things3
 end
end

并在相应的操作视图中,我正在检查这个

if can? :view, :test_case1
   #do things
end

所以问题是我在3个函数中调用了授权,我可以把它像单个一样,与before_filter相同

2 个答案:

答案 0 :(得分:3)

我不太清楚你的目标是什么,但load_and authorize_resource通常是最好的选择。如果您需要跳过控制器操作,可以执行以下操作:

class TestController
  load_and_authorize_resource
  skip_authorize_resource :only => :new
end

答案 1 :(得分:0)

将其添加到班级

class TestController
 load_and_authorize_resource
end

并且您不需要在每个操作中使用授权

https://github.com/ryanb/cancan/wiki/authorizing-controller-actions