是否可以调用“remote_function”?帮助程序文件中的方法而不是使用 Ruby on Rails 的控制器?
我正在使用 Ruby on Rails 3。我正在尝试使用 remote_function
并且我想从我的助手而不是控制器调用一个方法。
因此,在我的视图文件中,我有:
<%=
f.text_field :name, :id => "name_id",
:onkeyup => remote_function(
:update => "name_div",
:url => { :action => :method_name }
%>
实际上,将从控制器文件中调用以下方法(我也正确设置了路由器):
def method_name
...
end
我想在我的助手中移动 method_name
代码文件,然后从助手而不是控制器调用该方法(无需设置路由器)。 可以使用remote_function
吗?如果是这样,该怎么做?
I am using Ruby on Rails 3. I am trying to use the remote_function
and I would like to call a method from my helper instead of the controller.
So, in my view file I have:
<%=
f.text_field :name, :id => "name_id",
:onkeyup => remote_function(
:update => "name_div",
:url => { :action => :method_name }
%>
That, actually, will call the following method from the controller file (I properly set routers, as well):
def method_name
...
end
I would like to move the method_name
code in my helper file and then call that method from the helper instead of controller (without setting router). Is it possible using remote_function
? If so, how to do that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不幸的是,不可能使用remote_function直接调用辅助方法。所有remote_function 所做的就是生成一些JavaScript,这些JavaScript 可以向特定URL(从客户端)发出Ajax 请求。为了使该 URL 正常工作,必须设置路由和控制器操作来响应它。
如果您的目标是将代码移出控制器,则可以将操作方法放入一个模块中,并将该模块包含在一个或多个控制器类中。但是,您仍然需要将路由设置为指向每个控制器中的该方法/操作。
Unfortunately, it isn't possible to use remote_function to call a helper method directly. All remote_function does is generate some JavaScript that can make an Ajax request to a particular URL (from the client side). For that URL to work, the route and controller action have to be set up to respond to it.
If your goal is to move the code out of the controller, you could put the action method into a module and include that module in one or more controller classes. You would still need the routes set up to point to that method/action in each controller, however.