Rails ActionController 为每个操作执行相同的代码
对于那里的 Rails 专家,我想知道您将在哪里/如何为 Web 应用程序中的每个操作执行相同的代码?如果您能给我指出一篇文章或提供一个简短的代码片段,我将不胜感激。
预先感谢任何可以提供帮助的人。
To the rails experts out there I was wondering where/how you would execute the same code for every action in your web application? If you can point me to an article or provide a short code snippet I would greatly appreciate it.
Thanks in advance to anyone who can help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在 ApplicationController 中使用过滤器来运行应用程序中每个操作的代码。所有控制器都源自 ApplicationController,因此将过滤器放在那里将确保过滤器运行。
Use a filter in your ApplicationController to run the code for every action in your application. All your controllers descend from ApplicationController, so putting the filter there will ensure the filter gets run.
在我看来,您好像在谈论过滤器。
如果您希望每个控制器都运行过滤器,您也可以将过滤器放在 ApplicationController 上。
It sounds to me like you're talking about filters.
You can put the filter on the ApplicationController, too, if you want every controller to run it.
before_filter
如果您希望代码在每个操作“之前”执行。ApplicationController
中并在任何控制器中调用该方法。另一种方法是使用类似的帮助器:
在你的控制器中:
before_filter
if you want the code to be executed "before" each action.If you want the action to be declared each time you use it, you can put it in
ApplicationController
and call the method in any controller.Another approach is to use helpers like:
And in your controller: