Ruby on Rails - button_to using routes to call function from controller

Niko Adrianus Yuwono picture Niko Adrianus Yuwono · Aug 28, 2013 · Viewed 10.3k times · Source

Hello right now I've a problem about button_to

I want to setup a button that call a method in controller, this is how I setup the button :

(this located in issues/_edit.html.erb)

<%= button_to "Cancel Return", :action => "cancel_return", :controller => "issues" %>

and I want this will call this function in issues_controller.rb

  def cancel_return
    @issue.cancel_return(params)
  end

I also added it in the routes.rb

map.issue_cancel_return 'issues/cancel_return', :controller => 'issues',
                       :action => 'cancel_return'

but it can't work, I already tried to declare cancel_return as helper_method, but it also didn't work. is there any other solution? or I'm doing it wrong? I'm using ruby version 1.9.3p125 and rails version 2.3.15, I used old version because I tried to modify redmine, any help will be appreciated.

Thanks

Answer

dirtydexter picture dirtydexter · Aug 28, 2013

you should be putting them in a curly braces like this

<%= button_to "Cancel Return", { :controller => "issues", :action => "cancel_return"} %>

what happening is that map is not defining the method for the call like GET/POST/DELETE so what you can do is use this instead of you map line in your routes.rb file

get "issues/cancel_return" => "issues#cancel_return"

this should solve your problem.