如何指定before_filters的执行顺序?


68

rails是否对以下两种用法之一对执行过滤器之前的顺序做出任何保证:

before_filter [:fn1, :fn2]

要么

before_filter :fn1
before_filter :fn2

我将不胜感激。

Answers:


87

如果您参考http://api.rubyonrails.org/v2.3.8/classes/ActionController/Filters/ClassMethods.html,则有一个子标题为“过滤器链排序”,下面是示例代码:

class ShoppingController < ActionController::Base
    before_filter :verify_open_shop

class CheckoutController < ShoppingController
    prepend_before_filter :ensure_items_in_cart, :ensure_items_in_stock

根据解释:

该过滤器链的CheckoutController现在 :ensure_items_in_cart:ensure_items_in_stock:verify_open_shop.

因此,您可以像这样明确给出过滤器链的顺序。


正是我在寻找什么。@Johnny您的生活更加安全。非常感谢。
苏里亚

@Sector和JohnnyWoo:您对链接rails.rubyonrails.org/classes/ActionController/Filters/...去了死。
凯文

1
在3.2.14的轨道上,我得到的过滤器链如下::ensure_items_in_stock,:ensure_items_in_cart,:verify_open_shop
Raf


1
输出和调试确切过滤器链的命令将很有帮助。
Epigene '17

25

Rails中的Before_filter顺序 http://b2.broom9.com/?p=806

过滤器链排序 http://rails.rubyonrails.org/classes/ActionController/Filters/ClassMethods.html

如果您需要担保订单,可以这样做:

before_filter :fn3

def fn3
  fn1
  fn2
end

3
如果两者都失败,并尝试重定向,是否会引起问题?
Groxx 2011年

您可以在fn3中使用if,并将fn1,fn2的支票返回结果
部门

如果fn1失败(即返回false)并且不需要执行fn2,则必须添加更多逻辑。像这样的东西:fn1 ? fn2 : false
Eric H.

3

据我所知,您放置了要执行的第一个函数,依此类推。

因此,类似:

before_filter :fn1, :fn2

def fn1
  puts 'foo'
end

def fn2
  puts 'bar'
end

fn1然后执行fn2

希望能有所帮助。


我正在使用Rails 4,即使我的订单是:fn1, :fn2,:fn2也会被首先调用。
r3b00t

1

的过滤器链CheckoutController不遵循此顺序

:ensure_items_in_cart, :ensure_items_in_stock, :verify_open_shop

相反,它应该是

:ensure_items_in_stock, :ensure_items_in_cart, :verify_open_shop
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.