Rails控制器中针对特定操作的before_filter

33
  def new
    before_filter  do 
      redirect_to "/" unless current_admin || current_company
      flash[:notice] = 'You dont have enough permissions to be here' unless current_admin || current_company

     end
    CODE CODE CODE
   end

  def edit
    before_filter  do 
      redirect_to "/" unless current_admin.id = 5
      flash[:notice] = 'You dont have enough permissions to be here' unless current_admin || current_company

     end
    CODE CODE CODE
   end
这是我想要做的代码,但是我无法弄清楚如何正确实现。 我想要实现的是为每个操作应用一个before_filter规则。例如,一个用户可以访问INDEX操作但不能访问EDIT操作等等。 我知道before_filter方法只会运行一次,我不能运行4个before_filters,我只是提供一些参考因为我的英语很差。
你必须知道我正在使用Devise的current_admin和current_company方法。 我需要应用不同的过滤器(如果是管理员或者公司id=X)和其他操作。
非常感谢!我卡在这里了。 任何帮助将不胜感激。
1个回答

71

在你的 ApplicationController 方法中创建:

def check_privileges!
  redirect_to "/", notice: 'You dont have enough permissions to be here' unless current_admin || current_company
end

然后在你的控制器中:

before_filter :check_privileges!, only: [:new, :create, :edit, :save]

或者

before_filter :check_privileges!, except: [:index, :show]

说实话,我不知道你的方法也是可以接受的。 - Hauleth
17
在Rails 4及以上版本中,使用before_action代替before_filter - Chris Peters
1
我如何将参数传递给在 before_action 之后提到的 :some_function 函数? - Saravanabalagi Ramachandran
@ZekeDran 你不能这样做。唯一的解决方案是将lambda作为参数使用,然后你就可以做任何事情了。 - Hauleth
@Hauleth,为什么方法名后面要加上 ! - alexventuraio

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接