【发布时间】: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