views:

49

answers:

4

I'm new to Ruby on Rails (RoR). I created a new method on my controller. I want to call the new method from a view.

On my view, I have this code:

<%= link_to "MyMethod", :method=>:MyMethod %>

When I click on the link, the URL changes to http://localhost:3000/seats?method=MyMethod, and the page reloads on the browser and from the log I can see that MyMethod is never executed.

What can I do to call a method from a view?

A: 

Ops... the method thing, is not for calling a method but to describe an HTTP method. OK, so I shouldn't be using method. If i use :action=>"MyMethod"

the URL becomes seat/mymethod

which produces error, cannot find seat with id=mymethod how do I make it work?

A: 

The issue seems to lie within your routes (or you actually need a view helper as ndp suggests).

If a route is a better fit, go over the excellent rails routing guide. I can imagine one of two solutions:

  • map.resources :the_resource, :member => { :my_method => :get }: Use this if the method acts on one instance of the_resource. The URL would end up as follows: /the_resource/:id/my_method.
  • map.resources :the_resource, :collection => { :my_method => :get }: Use this if :my_method acts on many instances of the_resource - a collection. The URL would end up as: /the_resource/my_method.

Then run rake routes | grep my_method. What you'll find is the routing helpers generated by rails to access this method. You would call them either via my_method_the_resource(@an_instance) - for the member case, or my_method_the_resources for the collection case.

More information on section 3.11 of the linked guide.

hgimenez
A: 

assuming 'mymethod' was in a controller named 'users' and was pointing to an action 'mymethod' in your routes.rb add this:

map.my_method '/mymethod', :controller => 'users', :action => 'mymethod'

then in your view you can call it like this:

<%= link_to "MyMethod", my_method_path %>

Jen
A: 

Thanks guys, I guess I will have to read more about view helpers now. Rafael