在 Rails 中,有什么方法可以在控制器和视图中使用 app/helpers/foo.rb 方法吗?
看来app/helpers/foo.rb中的那些helpers可以在View中使用,但不能在Controller中使用?
在某些情况下,不同的控制器可能需要使用相同的方法,但只是传递不同的参数,因此在这种情况下,在控制器中使用助手是否有意义?
It seems that those helpers in app/helpers/foo.rb can be used in View, but cannot be used in Controller?
In some cases, different controllers may need to use the same method but just pass in a different parameter, so in that case, won't it make sense to use a helper in a controller?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在控制器之间重用代码有两种主要方法。
您可以创建
ApplicationController
的子类,其中包含公共代码,然后想要共享代码的控制器从新控制器类继承。 (或者,如果需要由所有控制器共享,则只需将代码添加到ApplicationController
本身。)或者,您可以创建自己的模块(这本质上是所有帮助程序)并将它们包含到控制器中 由于助手只是模块
,您可以在控制器中包含助手,但助手更多地用于视图层而不是控制器,因此它很少是在控制器之间共享代码的地方。
There are two main ways to re-use code between controllers.
You can create a subclass of
ApplicationController
which has the common code in and then your controllers that want to share the code inherit from the new controller class. (Or just add the code toApplicationController
itself if it needs to be shared by all controllers.)Alternatively you can create your own modules (this is all the helpers are in essence) and include them into the controllers that you want to use the code in.
As helpers are just modules you could include a helper in your controller but helpers are more for the view layer than the controller so it is rarely the place to share code between controllers.
这可能有道理,但事实并非如此。 (如果有人知道如何做到这一点,请随时发帖)
您可以将常见的帮助程序放入
ApplicationController
中,它们可以从应用程序中的任何控制器访问。It might make sense, but it doesn't work that way. (If anyone knows how to do that, feel free to post)
You can put common helpers in
ApplicationController
, they'll be accessible from any controller in your app.如上所述,您可以将通用助手放在 ApplicationController 或子类中。我想补充一点,以使它们也可供视图使用,您将其放在类的顶部:
As mentioned above, you can put common helpers in ApplicationController or a subclass. I would add that to make them available to views as well, that you put at the top of the class: