Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add a simple link to set a boolean field in Rails - nothing seems to happen

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?

like image 952
robintw Avatar asked Jan 20 '23 15:01

robintw


2 Answers

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 %>

like image 50
James Chen Avatar answered Jan 23 '23 06:01

James Chen


Your route is expecting a PUT request. Try this:

<%= link_to "I want to buy this present", taken_toggle_present_path(@present), :method => :put %>
like image 32
Dylan Markow Avatar answered Jan 23 '23 05:01

Dylan Markow