Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on Rails - Call controller method from a view

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.

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.

like image 529
glchan79 Avatar asked May 23 '12 05:05

glchan79


2 Answers

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:

  1. javascript to request a route and populate its DOM object when the button is clicked

  2. an action that returns whatever the ajax request was asking for

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

Old answer...

Declare a helper_method, like so:

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

like image 97
jimworm Avatar answered Oct 12 '22 23:10

jimworm


You can check the documentation for the button_to view helper

This is one way, of course, you could use the remote option to do this via an AJAX request.

like image 30
Alok Swain Avatar answered Oct 13 '22 00:10

Alok Swain