【问题标题】:Rails before_action not called on reloadRails before_action 未在重新加载时调用
【发布时间】:2020-12-10 15:52:47
【问题描述】:

我在 WordPress 站点的子目录中部署了一个 Rails 应用程序 (5.2.4.1)。我的控制器调用 before_action 方法来验证用户身份

class ClientsController < ApplicationController
  before_action :authenticate unless ENV["RAILS_ENV"] == "development"
  before_action :set_agent
  before_action :set_client, only: [:show, :edit, :update, :destroy]

如果用户没有来自域上另一个站点的 cookie,则调用 ApplicationController 中的方法进行重定向

class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception

  private
  def authenticate
    logger.info("Authenticate method called") # outputs on first load, not subsequent
    if request.cookies.collect{|c| c.grep(/cookiename/)}.blank?
      redirect_to 'https://example.com', status: :moved_permanently and return
    end
  end

如果我使用私人浏览器(所以没有 cookie)并尝试访问控制器,我会按预期重定向。

如果我输入相同的 URL,则不会调用 authenticate 方法。控制器呈现动作。我在 authenticate 方法中添加了一条日志语句,并且在进一步的页面加载时不会调用它。

我做错了吗?我希望在每次页面加载时调用 before_action 方法。其他两个(set_agent 和 set_client)可能也没有被调用,但由于它们根据路由参数设置实例变量,因此不会导致问题。

【问题讨论】:

  • 您的before_action 看起来在unless 之后缺少一个冒号,在它之前缺少一个逗号,这在技术上是有效的Ruby 代码,但它并不能满足您的要求。试试这个,也可以用更好的方法检查环境:before_action :authenticate, unless: proc { Rails.env.development? 我不相信它会导致你的症状,但我不认为代码是你最初想要的。

标签: ruby-on-rails ruby-on-rails-5 applicationcontroller


【解决方案1】:

你应该使用正确的 before_action 语法

class ClientsController < ApplicationController
  before_action :authenticate, :unless => ENV["RAILS_ENV"] == "development"
  .
  .
  .

还有一些例子

before_action :verify_authenticity_token_with_exception, :only => [:update_data], :unless => :ignore_csrf?
before_filter :authenticate_user!, :except => [:some_method]

【讨论】:

  • 他使用了正确的语法。您使用的语法是“旧”版本。
【解决方案2】:

问题出在我是如何检查没有 cookie 的。

request.cookies.collect{|c| c.grep(/cookiename/)}.blank?

会在有 cookie 和 [[], [], []].blank 的页面加载时返回一个空数组(例如 [[], [], []] )吗?评估为假。

这不是我想要的。

我切换到通过密钥检查 cookie(这应该首先发生),这解决了问题。

我确实知道为什么我在后续加载时没有看到记录器输出。我想我只是错过了它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-01-20
    • 1970-01-01
    • 2014-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-10
    相关资源
    最近更新 更多