在Rails MVC中,你可以从一个视图中调用一个控制器的方法(因为一个方法可以被称为来自帮助器的调用)?如果有,怎么样?
这是答案:
class MyController < ApplicationController
def my_method
# Lots of stuff
end
helper_method :my_method
end
然后,在您的视图中,您可以在ERB中引用它与<%
或<%=
完全相同:
<% my_method %>
您可能希望将方法声明为“helper_method”,或者将其移动到帮助程序。
从来没有尝试过,但调用公共方法类似于:
@controller.public_method
和私人方法:
@controller.send("private_method", args)
查看更多详情here
使用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。