Rails3 button_to invokes a POST action, trying to invoke a PUT action

I have a button_to that I want to perform a PUT action (there is only one thing that can be updated about this resource - it will be updated as "recognized", so there are no other form fields related to launching the action).

This is in my opinion (the controller is explicitly indicated because the button is on a view belonging to another controller):

<%= button_to "Acknowledged", :controller => 'practice_sessions', :id => @practice_session.id, :method => :put %> 

In my routes file, the resource was declared as a backup resource:

  resources :practice_sessions 

The controller for this resource has a create and update action, and the button_to above invokes the create action. I want it to trigger an update action.

This happens through the log before the create action fires:

 Started POST "/practice_sessions?id=21&method=put" for 127.0.0.1 at 2010-11-17 08:52:46 +0000 Processing by PracticeSessionsController#create as HTML Parameters: {"authenticity_token"=>"1EW0IlI38d0f4wST5azrCEZVZPfih7i0UvCGSF7eqbc=", "id"=>"21", "method"=>"put"} 
+6
ruby-on-rails ruby-on-rails-3 actionview
source share
3 answers

Your syntax is slightly off. button_to takes three arguments: the button title, the options hash, and the html_options hash. :method=>:put need to go to html_options , while route parameters should go to options . Therefore, you can rewrite it like this:

 <%= button_to "Acknowledged", { :controller => 'practice_sessions', :id => @practice_session.id}, :method => :put %> 

When clicked, the request should be processed by PracticeSessionsController#update

+17
source share

You may need to explicitly pass the argument :method => :put in the html_options hash string - it may fall into the options hash.

Try the following:

 <%= button_to "Acknowledged", { :controller => 'practice_sessions', :id => @practice_session.id }, :method => :put %> 

(Note the explicit brackets around :controller and :id )

+1
source share

In the end, I decided to go with a more relaxed approach, using named routes, which seem to work fine. I am still not 100% sure why the other method does not work, but I do not think it is important because it looks like a) more accurate and b) more conditional.

 <%= button_to "Acknowledge", practice_session_path(@practice_session), :method => :put %> 
+1
source share

All Articles