Rails before_filter用于控制器中的特定操作 [英] Rails before_filter for specific actions in controller

查看:182
本文介绍了Rails before_filter用于控制器中的特定操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  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,我只是给一些参考,因为我可怜的英语。

This is the code that I want to do, but I cant figure out how to do it right. What I want to achieve is to apply a before_filter rule for each of my actions. So perhaps a User can acces de INDEX action but not the EDIT action etc. I know that the before_filter method runs a single time, and I cannot run 4 before_filters, I'm just giving some reference because of my poor english.

您必须知道我正在使用Devise作为current_admin和current_company方法。
我需要应用不同的过滤器(如果管理员或如果company.id = X)和其他操作。

You must know that I am using Devise for the current_admin and current_company methods. I need to apply different filters (if admin or if company.id = X) and other actions.

提前感谢,我很累。
任何帮助将不胜感激。

Thanks in advance, I am pretty stucked in here. Any help will be appreciated.

推荐答案

在您的 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]

这篇关于Rails before_filter用于控制器中的特定操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆