将辅助方法包含到控制器中
我是 Rails 新手,我有一个关于助手和控制器的小问题。是否可以将我的自定义助手包含到控制器中?
假设我有这个助手类。
Module UsersHelper
def my_helper
...
end
end
然后我就有了这个控制器。
class UsersController < ApplicationController
end
我可以在控制器中使用 my_helper 吗?
I'm new to rails and I have this small problem about helpers and controllers. Is it possible to include my custom helper to a controller?
Let's say I have this helper class.
Module UsersHelper
def my_helper
...
end
end
Then I have this controller.
class UsersController < ApplicationController
end
Can I use the my_helper in my controller?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的 - 有多种方法,尤其是将助手包含(混合)到控制器中,或使用漏洞 在这里解释
但是......如果很难做到,或者导致代码丑陋,那么它可能不是正确的方法。是否可以将助手中的方法移至控制器中,然后使用“helper_method”将其委托回助手?
Yes - There are several ways, not least including (mixing-in) the helper into the controller, or using the loophole explained here
But... if it's hard to do, or results in ugly code, it may not be the right way to do it. Can the method that's in the helper not be moved into the controller, and then delegated back to the helper using "helper_method"?
是的。您可以使用
include
来完成,但我不建议您这样做。由于 Rails 是在 MVC 架构下构建的,因此您可以在控制器中包含 UserHelper 之前了解有关 MVC 的更多信息。MVC 参考:
http://guides.rubyonrails.org/getting_started.html#the- mvc架构
模型-视图-控制器
Yes. you can do by using
include
, but I don't recommend you doing this. Because Rails constructs under MVC architecture, you can learn more about MVC before include UserHelper in your controllers.MVC Reference:
http://guides.rubyonrails.org/getting_started.html#the-mvc-architecture
Model–view–controller