如果请求是 xhr,Rails 有没有办法跳过 before_filter? [英] Is there a way in Rails to skip a before_filter if the request is xhr?
问题描述
使用以下代码:
class TestsController < ApplicationController
skip_before_filter :load_something, # how to skip these only
:load_something_else # if the request is xhr ?
def index
respond_to do |format|
format.html
format.js
end
end
end
有没有办法跳过过滤器之前的过滤器,具体取决于请求是否是 javascript 调用而不更改 :load_something
和 :load_something_else
方法?
Is there a way to skip before filters depending if the request is a javascript call without changing the :load_something
and :load_something_else
methods ?
谢谢!
推荐答案
过去没有干净的解决方案.假设您无法控制 before_filters
(或不想更改它们),我会保留 skip_before_filter
并添加一个额外的 before_filter
如果它是 xhr
方法,则仅执行所需的方法.
There used to be no clean solution to this. Assuming you do not have control over the before_filters
(or do not want to change them), i would leave the skip_before_filter
and add an extra before_filter
that only executes the wanted methods if it is an xhr
method.
有点像
skip_before_filter :load_something, # how to skip these only
:load_something_else # if the request is xhr ?
before_filter :do_loads_if_xhr
def do_loads_if_xhr
if request.xhr?
load_something
load_something_else
end
end
此处描述的方法仅适用于应用程序的全局条件:仅在创建类时评估条件.不是针对每个请求.
The method described here only works because the conditional is global for the application: the conditional is only evaluated when the class is created. Not on each request.
[更新]然而,有一种更简洁的方法可以使 skip_before_filter
成为条件.像这样写:
[UPDATED]
There is however, a cleaner way to make the skip_before_filter
conditional. Write it like this:
skip_before_filter :load_something, :load_something_else, :if => proc {|c| request.xhr?}
另请注意,虽然 skip_before_filter
仍然完全受支持,并且没有被弃用,但由于 Rails 4,文档似乎更喜欢(相同的)skip_before_action
.此外,文档对此完全不清楚,必须在代码中进行验证.
Also note that while skip_before_filter
is still completely supported, and not deprecated, since rails 4 the documentation seems to prefer the (identical) skip_before_action
. Also the documentation is totally not clear about this, had to verify in code.
这篇关于如果请求是 xhr,Rails 有没有办法跳过 before_filter?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!