加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 如何使before_action在所有控制器和操作之外运

发布时间:2020-12-16 22:35:55 所属栏目:百科 来源:网络整理
导读:我有一个rails 4.2.x应用程序,设计用于身份验证 – 我有几个控制器. 我想要devicate authenticate_user!在所有控制器和操作上运行的方法,除了家庭控制器索引操作. (当然,authenticate_user!本身就注意设计出一些动作,比如login through) 我可以确保每个控
我有一个rails 4.2.x应用程序,设计用于身份验证 – 我有几个控制器.

我想要devicate authenticate_user!在所有控制器和操作上运行的方法,除了家庭控制器索引操作. (当然,authenticate_user!本身就注意设计出一些动作,比如login through)

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

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

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

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

但是我看不到如何使家庭/索引成为例外.

我当然可以手动添加before_action:authenticate_user!到每个控制器,并为索引操作的归属控制器添加一个异常.但是这不是很干,如果我添加新的控制器,我需要记住将这个before_action添加到它们中.

解决方法

你要做的是设置autheticate_user!在所有控制器上:
class ApplicationController < ActionController::Base
  before_action :authenticate_user!
  ...
end

然后在您的HomeController上,您可以这样做:

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

希望这会帮助你!

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读