Ruby-on-rails Rails before_filter 用于控制器中的特定操作
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10061373/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Rails before_filter for specific actions in controller
提问by Mau Ruiz
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
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.
这是我想要做的代码,但我不知道如何正确地做。我想要实现的是为我的每个操作应用 before_filter 规则。因此,也许用户可以访问 INDEX 操作,但不能访问 EDIT 操作等。我知道 before_filter 方法运行一次,而我不能运行 4 个 before_filters,由于我的英语不好,我只是提供一些参考。
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.
您必须知道我将 Devise 用于 current_admin 和 current_company 方法。我需要应用不同的过滤器(如果是管理员或如果 company.id = X)和其他操作。
Thanks in advance, I am pretty stucked in here. Any help will be appreciated.
提前致谢,我很困在这里。任何帮助将不胜感激。
回答by Hauleth
Create in your ApplicationControllermethod:
在您的ApplicationController方法中创建:
def check_privileges!
redirect_to "/", notice: 'You dont have enough permissions to be here' unless current_admin || current_company
end
And then in your controller:
然后在您的控制器中:
before_filter :check_privileges!, only: [:new, :create, :edit, :save]
Or
或者
before_filter :check_privileges!, except: [:index, :show]

