将辅助方法包含到控制器中

发布于 2024-11-16 18:10:08 字数 304 浏览 4 评论 0原文

我是 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

你与昨日 2024-11-23 18:10:08

是的 - 有多种方法,尤其是将助手包含(混合)到控制器中,或使用漏洞 在这里解释

但是......如果很难做到,或者导致代码丑陋,那么它可能不是正确的方法。是否可以将助手中的方法移至控制器中,然后使用“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"?

妞丶爷亲个 2024-11-23 18:10:08

是的。您可以使用 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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文