I’m trying to add a link to a Rails view to set a boolean field to true when it is clicked. In the controller (present_controller.rb) I have the following code:
def taken_toggle
@matching = Present.find(params[:id])
@matching.taken = true
@matching.save
end
and in the associated view I have the following code:
<%= link_to "I want to buy this present", :url => {:action => "taken_toggle", :id => @present.id} %>
However, when I click the button nothing happens. If I go back to the main list the boolean field has not been updated. In the log I get the following:
Started GET "/presents/2/edit?url[action]=taken_toggle&url[id]=2" for 152.78.101.154 at Sun Jan 30 04:56:34 -0800 2011
Processing by PresentsController#edit as HTML
Parameters: {"url"=>{"action"=>"taken_toggle", "id"=>"2"}, "id"=>"2"}
Rendered presents/_form.html.erb (6.0ms)
Rendered presents/edit.html.erb within layouts/application (10.0ms)
Completed 200 OK in 13ms (Views: 10.7ms | ActiveRecord: 0.9ms)
I’m sure I’m missing something really simple – does anyone know what it is?
Update: I’ve added the route and rake routes is now giving the following line (amongst all the normal routes):
taken_toggle_present PUT /presents/:id/taken_toggle(.:format) {:controller=>"presents", :action=>"taken_toggle"}
What should I change the link to so as to make it work? At the moment the link is still:
<%= link_to "I want to buy this present", :url => {:action => "taken_toggle", :id => @present.id} %>
But that seems right to me, as it is going to the right action, and passing in the ID. Any ideas?
Update:
I’ve tried the latest answers, but both of them lead to the following log error:
Started GET "/presents/2/taken_toggle" for 86.150.141.2 at Fri Feb 04 01:37:23 -0800 2011
ActionController::RoutingError (No route matches "/presents/2/taken_toggle"):
This seems slightly strange given the output of rake routes above. Any ideas?
link_todoesn’t accept a:urloption, so it’s translating everything in your:urlhash to GET parameters: you can see them in the request path in your logs:You should just be able to take out the
:url => { }part to make the link work:However, in general the preferred way to specify a link to a restful action is using a path helper: