如何在所有控制器和操作之外运行before_action?

Ana*_*and 23 ruby-on-rails callback devise

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

我想要设计authenticate_user!除了在主控制器索引操作之外的所有控制器和操作上运行的方法.(当然,authenticate_user!本身注重设计登录等操作)

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

class ApplicationController < ActionController::Base
  before_action :authenticate_user!
  ...
end
Run Code Online (Sandbox Code Playgroud)

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

class ApplicationController < ActionController::Base
  before_action :authenticate_user!, except: [:index]
  ...
end
Run Code Online (Sandbox Code Playgroud)

但我不知道如何让home/index成为例外.

当然,我可以手动添加before_action :authenticate_user!到每个控制器,并为主控制器添加一个例外以进行索引操作.但这不是很干,如果我添加新的控制器,我需要记住将这个before_action添加到每个控制器.

I'm*_*ADR 48

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

class ApplicationController < ActionController::Base
  before_action :authenticate_user!
  ...
end
Run Code Online (Sandbox Code Playgroud)

然后在你的HomeController上你做到了:

class HomeController < ApplicationController
  skip_before_action :authenticate_user!, only: [:index]
  ...
end
Run Code Online (Sandbox Code Playgroud)

希望对你有帮助 !