过滤器出现之前的顺序是什么? [英] What order do before filters occur in?
问题描述
过滤器出现之前的顺序是什么?具体来说,关于inheiritance,before_action过滤器出现了什么顺序?例如,这是否有效:
What order do before filters occur in? Specifically, what order do the before_action filters occur in, in regards to inheiritance? For example, will this work:
class A < ActionController::Base
before_action :set_user
def set_user
@user = something
end
end
class B < A
before_action :set_post
def show
render @post
end
def set_post
@post = @user.posts.first
end
end
B#show会工作吗?筛选顺序有哪些规则供将来参考?我在Rails文档中找不到任何这个。
Will "B#show" work? What are the rules for filter order for future reference? I can't find any of this in the Rails documentation.
推荐答案
我建议看一下 源代码 和<过滤器上的strong> API文档 。
I suggest taking a look at the source code and API Docs on filters.
默认订购应为
-
:set_post
-
:set_user
:set_post
:set_user
我认为如果您想将:set_user
推到堆栈顶部,您可以更改 A
到
I think if you wanted to push :set_user
to the top of the stack you could change the line in A
to
prepend_before_action :set_user
另外值得指出的是,这不是关于该主题的唯一问题;这里有其他人 。
Also worth pointing out, this isn't the only question on the topic; there are others here on SO.
至于您的具体情况,您似乎需要更改 A
正如我上面提到的那样,为了 @user
在 set_post
中分配 B
运行。
As for your specific situation, it looks like you'll need to change A
as I mentioned above in order to have @user
be assigned by the time set_post
in B
runs.
自4.2.6起(可能已更改)在早期版本中,订购现在是孩子之前的父母:
As of 4.2.6 (probably changed in an earlier version), the ordering is now parent before child:
-
:set_user
-
:set_post
:set_user
:set_post
这篇关于过滤器出现之前的顺序是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!