控制器调用助手
我有一个简单的问题: 将控制器多次调用的辅助方法放在哪里?
我的愿望是保持我的控制器(user_controller)清晰,并且我有一个被多次调用的辅助方法(check_permits) 是否可以将此方法放入 user_helper 中?
如果是==>如何在user_controller内部调用它?如果我只记得 check_permits 它无法识别它。
如果没有==>,辅助方法放在哪里?
I have an easy question:
Where to put the helper methods that is called many times by a controller ?
My wish is to keep clear my controller ( user_controller) and I have an helper methods that is called many times (check_permits)
is it possible to put this method inside user_helper ?
If yes ==> how to recall it inside user_controller ? If I simply recall check_permits it doesen't recognize it.
If no ==>, where to put the helper methods ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您正在使用令人困惑的术语。在 Rails 中,控制器没有助手。助手被定义为用于视图。可以使用“helpers”方法从控制器调用辅助方法(请参阅 http ://api.rubyonrails.org/classes/ActionController/Helpers/ClassMethods.html),但我认为这不是您正在寻找的(而且通常这也不是一个好主意)。
您可能想要的是(1)将该方法作为受保护方法直接放入 users_controller.rb 中:
或者(2)如果从多个控制器调用它,则将其放入 application_controller.rb 中。
或者 (3) 将其作为模块放入库文件中,并将其包含在任何需要它的控制器中。例如,您可以创建 lib/check_permits.rb:
然后在 users_controller.rb 中:
You are using confusing terminology. In rails, controllers do not have helpers. Helpers are defined as being for the views. It's possible to call helper methods from a controller by using the "helpers" method (see http://api.rubyonrails.org/classes/ActionController/Helpers/ClassMethods.html), but I don't think that's what you're looking for (and generally that's not a good idea anyway).
What you probably want is to either (1) put the method directly in your users_controller.rb as a protected method:
Or (2) put it in the application_controller.rb if you call it from multiple controllers.
Or (3) put it in a library file as a module and include it in whatever controllers need it. For example, you might create lib/check_permits.rb:
And then in users_controller.rb:
您可以将全局帮助程序方法放入 application_helper.rb 文件中,但如果它仅由一个控制器使用,则每个控制器都可以拥有自己的帮助程序文件。查看应用程序/帮助程序(或应用程序/控制器/帮助程序)。
You can put global helper methods in the application_helper.rb file, but if it's only to be used by one controller each controller can have it's own helper file. Look in app/helper (or app/controller/helper).