Ruby-on-rails Rails 4:before_filter 与 before_action
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16519828/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Rails 4: before_filter vs. before_action
提问by freemanoid
In rails >4.0.0 generators creates CRUD operations with before_actionnot before_filter. It seems to do the same thing. So what's the difference between these two?
在 rails >4.0.0 中,生成器使用before_actionnot 来创建 CRUD 操作before_filter。它似乎做同样的事情。那么这两者有什么区别呢?
回答by freemanoid
As we can seein ActionController::Base, before_actionis just a new syntaxfor before_filter.
正如我们所看到的ActionController::Base,before_action只是一个新的语法的before_filter。
However all before_filterssyntax are deprecatedin Rails 5.0and will be removed in Rails 5.1
然而,所有before_filters语法在Rails 5.0 中都被弃用,并将在Rails 5.1 中删除
回答by Awais
It is just syntax difference, in rails app there is CRUD, and seven actions basically by name index, new, create, show, update, edit, destroy.
这只是语法差异,在 Rails 应用程序中有 CRUD,七个动作基本上按名称index、new、create、show、update、edit、destroy。
Rails 4 make it developer friendly to change syntax before filterto before action.
Rails 4 使开发人员更友好地将过滤器之前的语法更改为操作之前。
before_actioncall method before the actions which we declare, like
before_action在我们声明的动作之前调用方法,比如
before_action :set_event, only: [:show, :update, :destroy, :edit]
set_eventis a method which will call always before show, update, edit and destroy.
set_event是一个总是在显示、更新、编辑和销毁之前调用的方法。
回答by Matthias
It is just a name change. before_actionis more specific, because it gets executed before an action.
这只是更名。before_action更具体,因为它在操作之前执行。
回答by Pankaj Dhote
before_filter/before_action: means anything to be executed before any action executes.
before_filter/before_action:意味着在任何动作执行之前要执行的任何操作。
Both are same. they are just alias for each other as their behavior is same.
两者都是一样的。他们只是彼此的别名,因为他们的行为是相同的。
回答by yusefu
To figure out what is the difference between before_action and before_filter, we should understand the difference between action and filter.
要弄清楚 before_action 和 before_filter 之间有什么区别,我们应该了解 action 和 filter 之间的区别。
An action is a method of a controller to which you can route to. For example, your user creation page might be routed to UsersController#new - new is the action in this route.
操作是您可以路由到的控制器的方法。例如,您的用户创建页面可能会路由到 UsersController#new - new 是此路由中的操作。
Filters run in respect to controller actions - before, after or around them. These methods can halt the action processing by redirecting or set up common data to every action in the controller.
过滤器根据控制器动作运行 - 在它们之前、之后或周围。这些方法可以通过将公共数据重定向或设置到控制器中的每个动作来停止动作处理。
Rails 4 –> _action
Rails 3 –> _filter
Rails 4 –> _action
Rails 3 –> _filter

