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?
It seems you're on a rails 3 app. Getting methods (GET, PUT) and routes right should work.
The routes part, either define taken_toggle in the presents resource, like this:
resources :presents do member do put :taken_toggle end end
or just use match as Nikita has suggested:
match 'presents/:id/taken_toggle', :as => "taken_toggle_present", :to => "presents#taken_toggle"
Now the link part:
<%= link_to "I want to buy this present", taken_toggle_present_path(@present), :method => :put %>
Your route is expecting a PUT request. Try this:
<%= link_to "I want to buy this present", taken_toggle_present_path(@present), :method => :put %>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With