Ruby on Rails - 从视图调用控制器方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10714119/
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
Ruby on Rails - Call controller method from a view
提问by glchan79
Sorry, I have a Rails newbie question. In my Rails application, how can I call a method defined in my controller from the view? For example, let's say I wrote a custom method that retrieves stock information. In my view, I want to have a regular HTML button, that upon clicking, will call my custom method and populate the stock results.
抱歉,我有一个 Rails 新手问题。在我的 Rails 应用程序中,如何从视图调用控制器中定义的方法?例如,假设我编写了一个检索股票信息的自定义方法。在我看来,我想要一个常规的 HTML 按钮,点击后会调用我的自定义方法并填充股票结果。
How is that done? I've looked around and couldn't find a straightforward way to do this. But I'm sure I'm missing something here.
这是怎么做的?我环顾四周,找不到一个简单的方法来做到这一点。但我确定我在这里遗漏了一些东西。
回答by jimworm
Edit: I took the question by its title which wasn't what the question was. The answer to the title of your question is at the bottom
编辑:我按标题回答了这个问题,这不是问题所在。问题标题的答案在底部
What you want is an ajax request, which is a separate controller action. You'll need:
你想要的是一个ajax请求,它是一个单独的控制器动作。你需要:
javascript to request a route and populate its DOM object when the button is clicked
an action that returns whatever the ajax request was asking for
javascript 请求路由并在单击按钮时填充其 DOM 对象
返回 ajax 请求所要求的任何内容的操作
There are many ways to do this, but if you search for "howto rails ajax" you'll find a gazillion tutorials to help you on your way. One way that I like is called pjax: https://github.com/rails/pjax_rails
有很多方法可以做到这一点,但是如果您搜索“howto rails ajax”,您会找到大量教程来帮助您。我喜欢的一种方式称为 pjax:https: //github.com/rails/pjax_rails
Old answer...
旧答案...
Declare a helper_method, like so:
声明 a helper_method,像这样:
In your controlller:
在您的控制器中:
private
def find_stock
...
end
helper_method :find_stock
In your view:
在您看来:
<% find_stock.each do |stock| -%>
Documentation: http://api.rubyonrails.org/classes/AbstractController/Helpers/ClassMethods.html#method-i-helper_method
文档:http: //api.rubyonrails.org/classes/AbstractController/Helpers/ClassMethods.html#method-i-helper_method

