Ruby on rails 在Ajax请求的情况下使用before\u操作钩子

Ruby on rails 在Ajax请求的情况下使用before\u操作钩子,ruby-on-rails,ruby-on-rails-5,Ruby On Rails,Ruby On Rails 5,我的一些控制器在执行操作之前有钩子,以确保模型实例属于正确的用户,或者用户经过身份验证 before_action :authenticate_user! before_action :check_owner private def check_owner Unless current_user.id == Myobject.find(params[:id]).user.id redirect_to root_path end 现在我想知道如果我做一个Ajax请求(remote:t

我的一些控制器在执行操作之前有
钩子,以确保模型实例属于正确的用户,或者用户经过身份验证

before_action :authenticate_user!
before_action :check_owner

private

def check_owner
  Unless current_user.id == Myobject.find(params[:id]).user.id
  redirect_to root_path
end
现在我想知道如果我做一个Ajax请求(
remote:true
参数到一个表单),在没有用户被验证的情况下,
before\u操作
钩子会通过吗?至少我猜重定向会失败


如果钩子能起作用,那么我很高兴。但也许有更好的方法来实现这一点,或者让重定向工作起来

remote:true
的情况下,
before_action
仍然会停止请求,但是正如您所提到的,上面的重定向仅适用于HTML格式的请求。处理JS请求重定向的最佳方法是在
ApplicationController
中添加自己的方法来处理所有所需的请求格式:

class ApplicationController < ActionController::Base
  ...

  def all_formats_redirect_to(path)
    respond_to do |format|
      format.html { redirect_to path }
      format.js { render js: "window.location = #{path.to_json}" }
      # you can add how you want to handle redirect for other formats if you use them
    end
  end

  ...
end

非常感谢,在全球范围内处理这件事绝对是一个非常好的主意。
before_action :authenticate_user!
before_action :check_owner

private

def check_owner
  unless current_user.id == Myobject.find(params[:id).user_id
    all_formats_redirect_to(root_path)
    false
  end
end