Rails 4:before_filter vs. before_action

本文翻译自:Rails 4: before_filter vs. before_action

In rails >4.0.0 generators creates CRUD operations with before_action not before_filter . 在rails> 4.0.0中,生成器使用before_action而不是before_filter创建CRUD操作。 It seems to do the same thing. 它似乎做同样的事情。 So what's the difference between these two? 那么这两者之间的区别是什么?


#1楼

参考:https://stackoom.com/question/17JYq/Rails-before-filter-vs-before-action


#2楼

As we can see in ActionController::Base , before_action is just a new syntax for before_filter . 正如我们在ActionController::Base 看到的那样, before_action只是before_filter一种新语法

However all before_filters syntax are deprecated in Rails 5.0 and will be removed in Rails 5.1 但是,在Rails 5.0 中不推荐使用所有before_filters语法并且将在Rails 5.1中删除它们


#3楼

It is just a name change. 这只是名称的变化。 before_action is more specific, because it gets executed before an action. before_action更具体,因为它在动作之前执行。


#4楼

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 app中有CRUD,七个动作基本上都是通过名称索引新建创建显示更新编辑销毁

Rails 4 make it developer friendly to change syntax before filter to before action . Rails 4使得开发人员可以在过滤操作 之前更改语法。

before_action call method before the actions which we declare, like 我们声明的动作之前的before_action调用方法,如

before_action :set_event, only: [:show, :update, :destroy, :edit]

set_event is a method which will call always before show, update, edit and destroy. set_event是一个在显示,更新,编辑和销毁之前始终调用的方法。


#5楼

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 4 - > _action

Rails 3 –> _filter Rails 3 - > _filter


#6楼

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. 它们只是彼此的别名,因为它们的行为是相同的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值