如何使before_action在所有控制器和操作之外运行,除了一个? [英] How do I make a before_action to run on all controllers and actions except one?

查看:823
本文介绍了如何使before_action在所有控制器和操作之外运行,除了一个?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个rails 4.2.x应用程序,设计用于身份验证 - 我有几个控制器。



我想要设计者authenticate_user!在所有控制器和操作上运行的方法,除了主控制器索引操作。 (当然,authenticate_user!本身会注意设计出一些动作,例如登录)//

我可以确保每个控制器操作在application_controller.rb中运行before_action:

  class ApplicationController< ActionController :: Base 
before_action:authenticate_user!
...
end

我还可以限制一组特定的操作在所有控制器:

  class ApplicationController< ActionController :: Base 
before_action:authenticate_user !,除了:[:index]
...
end

但是我没有看到如何使home / index成为一个例外。



当然,我可以手动向每个控制器添加 before_action:authenticate_user!,并向家庭控制器的索引动作。但是这不是很干,如果我添加了新的控制器,我需要记住将这个before_action添加到每个控件中。

解决方案

p>你要做的是设置autheticate_user!在所有这样的控制器上:

  class ApplicationController< ActionController :: Base 
before_action:authenticate_user!
...
end

然后在您的HomeController上执行此操作:

  class HomeController< ApplicationController 
skip_before_action:authenticate_user !, only:[:index]
...
end

希望这将有助于您!


I have a rails 4.2.x app, with devise for authentication - I have several controllers.

I want the devise authenticate_user! method to be run on all controllers and actions except on the home controller index action. (Of course, authenticate_user! itself takes care that devise actions like login go through)

I can ensure that every controller action runs the before_action in application_controller.rb:

class ApplicationController < ActionController::Base
  before_action :authenticate_user!
  ...
end

I can also restrict a specific set of actions on all controllers:

class ApplicationController < ActionController::Base
  before_action :authenticate_user!, except: [:index]
  ...
end

But I don't see how to make just home/index to be an exception.

I could, of course, manually add before_action :authenticate_user! to every controller, and add an exception to the home controller for the index action. But this is not very dry, and if I add new controllers, I need to remember to add this before_action to each of them.

解决方案

What you have to do is to set autheticate_user! on all controllers like that :

class ApplicationController < ActionController::Base
  before_action :authenticate_user!
  ...
end

And then on your HomeController you do that :

class HomeController < ApplicationController
  skip_before_action :authenticate_user!, only: [:index]
  ...
end

Hope this will help you !

这篇关于如何使before_action在所有控制器和操作之外运行,除了一个?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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