Ruby-on-rails 我们可以从视图中调用 Controller 的方法吗(理想情况下我们从 helper 调用)?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8906527/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can we call a Controller's method from a view (as we call from helper ideally)?
提问by Manish Shrivastava
In Rails MVC, can you call a controller's method from a view (as a method could be called call from a helper)? If yes, how?
在 Rails MVC 中,您可以从视图中调用控制器的方法吗(因为方法可以从助手调用)?如果是,如何?
回答by sailor
Here is the answer:
这是答案:
class MyController < ApplicationController
def my_method
# Lots of stuff
end
helper_method :my_method
end
Then, in your view, you can reference it in ERB exactly how you expect with <%or <%=:
然后,在您看来,您可以在 ERB 中完全按照您的期望使用<%or引用它<%=:
<% my_method %>
回答by Pavling
You possibly want to declare your method as a "helper_method", or alternatively move it to a helper.
您可能希望将您的方法声明为“helper_method”,或者将其移至帮助程序。
回答by Wahaj Ali
回答by przbadu
make your action helper method using helper_method :your_action_name
使用 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
Or you can also make all actions as your helper method using: helper :all
或者,您也可以使用以下方法将所有操作作为辅助方法: helper :all
class ApplicationController < ActionController::Base
helper :all
def foo
# your foo logic
end
def bar
# your bar logic
end
end
In both cases, you can access foo and bar from all controllers.
在这两种情况下,您都可以从所有控制器访问 foo 和 bar。

