我们可以从视图中调用Controller的方法吗(就像我们从理想的帮助者那里调用的那样)?
那么,我知道这不应该在这里问,但我没有find一个更好的地方得到答案。 这个问题在一个好公司的采访中被问到。
在Rails MVC中,你可以从视图中调用一个控制器的方法(如我们从理想的帮助者调用)? 如果是的话,怎么样?
那个时候我无法回答那个问题。 你能帮忙吗?
答案是:
class MyController < ApplicationController def my_method # Lots of stuff end helper_method :my_method end 您可能想要将您的方法声明为“helper_method”,或者将其移至帮助程序。
helper和helper_method做了什么?
还没有尝试过,但调用公共方法类似于:
 @controller.public_method 
和私人方法:
 @controller.send("private_method", args) 
在这里看到更多细节
 使用helper_method :your_action_name使你的动作助手方法 
 class ApplicationController < ActionController::Base def foo # your foo logic end helper_method :foo def bar # your bar logic end helper_method :bar end 
 或者你也可以使用helper :all来做所有的动作 
  class ApplicationController < ActionController::Base helper :all def foo # your foo logic end def bar # your bar logic end end 
在这两种情况下,都可以从所有控制器访问foo和bar。