简体   繁体   English

Ruby on Rails - 从视图中调用控制器方法

[英]Ruby on Rails - Call controller method from a view

Sorry, I have a Rails newbie question. 对不起,我有一个Rails新手问题。 In my Rails application, how can I call a method defined in my controller from the view? 在我的Rails应用程序中,如何从视图中调用控制器中定义的方法? 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. 在我看来,我希望有一个常规的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. 但我确定我在这里遗漏了一些东西。

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. 你想要的是一个ajax请求,它是一个单独的控制器动作。 You'll need: 你需要:

  1. javascript to request a route and populate its DOM object when the button is clicked 单击按钮时,javascript请求路径并填充其DOM对象

  2. an action that returns whatever the ajax request was asking for 一个返回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. 有很多方法可以做到这一点,但如果你搜索“howto rails ajax”,你会找到一个无数的教程来帮助你。 One way that I like is called pjax: https://github.com/rails/pjax_rails 我喜欢的一种方式叫做pjax: https//github.com/rails/pjax_rails

Old answer... 老答案......

Declare a helper_method , like so: 声明一个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

You can check the documentation for the button_to view helper 您可以查看button_to查看帮助程序的文档

This is one way, of course, you could use the remote option to do this via an AJAX request. 这是一种方式,当然,您可以使用远程选项通过AJAX请求执行此操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM