如何在其帮助程序文件中显式包含控制器方法,以便可以将该帮助程序包含在另一个控制器中并使用该方法?
我正在使用 Ruby on Rails 3,并且希望在其相关帮助程序文件 (accounts_helper.rb) 中显式包含一个控制器 (accounts_controller.rb) 方法,以便我可以在另一个控制器中包含该帮助程序并使用其方法。我需要它,因为我可以在helper 中移出accounts_controller.rb 中所述的方法代码,但我需要在其他控制器中使用该方法。
由于这个问题也与这个其他问题相关,所以我想以这种方式解决后者:
(1)在accounts_controller.rb中我声明
def method_name
...
end
(2)在accounts_helper.rb中我可以包含method_name
...如何做到这一点?
( 3) 在 posts_account.rb 中,我可以包含accounts_helper.rb...如何做到这一点?
这是一个好方法吗?如果是这样,我该如何编写步骤 2 和 3 的代码?
I am using Ruby on Rails 3 and I would like to include a controller (accounts_controller.rb) method explicitly in its related helper file (accounts_helper.rb) so that I can include that helper in another controller and use its methods. I need that because I can move out in helper the method code stated in accounts_controller.rb, but I need to use that method in others controllers.
Since this question is also related to this other question, I thinked to solve the latter this way:
(1) in accounts_controller.rb I state
def method_name
...
end
(2) in accounts_helper.rb I can include the method_name
... how to do this?
(3) in posts_account.rb I can include accounts_helper.rb... how to do this?
Is it a good approach? If so, how can I code the steps 2 and 3?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您想跨控制器和视图/帮助器使用该方法,您可以
在您的
application_controller
中将其声明为
helper_method
这将使该方法跨控制器和视图可用If you want to use the method across controllers and views/helpers you can declare it as a
helper_method
In your
application_controller
This will make the method available across controllers and views
一个想法 - 将辅助方法放在 application_controller.rb 中,然后您可以声明何时将其公开给每个控制器的视图 - 或者在 application_controller.rb 中全局公开。
One idea -- put the helper method in application_controller.rb then you can declare when to expose it to the view in a per controller basis - or globally in the application_controller.rb.
如果您需要在多个控制器中使用该方法,那么我建议将其放在 application_controller.rb 中是合理的
If you need to use the method in multiple controllers then I'd suggest it's reasonable to put it in
application_controller.rb