views:

37

answers:

2

Using the rails button_to helper I'm trying to run the update method in a controller. I need to set the ID of the object being updated manually. The code I have I think should be right, but rails keeps trying to put the ID as part of a route.

in the view:

button_to ">", :controller=>'people', :action=>'update', 'person'=>{:team=>team_leader.team}, :id=>currently_viewing_person

in the controller:

  def update
    @person = Person.find(params[:id])
    #...rest of method
  end

The controller update method is never executed. The error on the web browser is:

Unknown action

No action responded to 3. Actions: create, index, new, search, show, and update

'3' was the value of currently_viewing_person

What's the correct way to pass :id so update can extract from params[:id]

A: 

Here's to reading the documentation again, and understanding that in a REST architecture, update is sent via PUT, not POST. The correct view code is:

button_to ">", {:controller=>'people', :action=>'update', 'person'=>{:team=>team_leader.team}, :id=>currently_viewing_person}, :method => :put

Oddly, if I view source on this page the form created by button_to shows POST being used:

<form method="post" ...

But the rails log confirms that PUT was indeed used:

Processing PeopleController#update (for 127.0.0.1 at 2010-07-15 00:10:09) [PUT]
SooDesuNe
Heh -- you beat me by seconds :) The reason for the `<form method="post"` is that browsers don't do PUTs (or DELETEs), so they emulate them with a POST. You'll see a "_method" => "put" or somesuch posted in the form data.
zetetic
A: 

button_to uses POST by default. For update you need a PUT, so pass in the method along with the other parameters:

button_to ">", 
  { :controller=>'people', :action=>'update',
    'person'=>{:team=>team_leader.team}, 
    :id=>currently_viewing_person }, 
  :method => :put

Note that the method has to be passed in as a separate hash

zetetic