routes – Why is my Rails web app calling the wrong action? – Education Career Blog

I’m diving into Ruby on Rails and I’m experiencing a weird bug, using Rails 3.0.1 and Ruby 1.8.7. Using the generated scaffold code, my “Show” action is getting called when I’m expecting my “Destroy” action to get called. Here’s the code…

routes.rb

webappdotcom::Application.routes.draw do
  resources :projects
  root :to => "home#index"
end

index.html.erb

<td><%= link_to 'Destroy', project, :confirm => 'Are you sure?', :method => :delete %></td>

actual HTML code that is rendered in browser

<td><a href="/projects/12" data-confirm="Are you sure?" data-method="delete" rel="nofollow">Destroy</a></td>

server output when I click on the “Destroy” link

Started GET "/projects/12" for 127.0.0.1 at Wed Oct 20 23:39:37 -0500 2010
  Processing by ProjectsController#show as HTML
  Parameters: {"id"=>"12"}
  Project Load (0.1ms)  SELECT "projects".* FROM "projects" WHERE ("projects"."id" = 12) LIMIT 1
Rendered projects/show.html.erb within layouts/application (9.0ms)
Completed 200 OK in 77ms (Views: 13.3ms | ActiveRecord: 0.1ms)

You can see the “ProjectsController#show” action is being called, but I want the “Destroy” action to be called. Also, I noticed the browser isn’t displaying the confirmation message “Are you sure?” either. Any ideas what could be causing this or what I’m missing?

Thanks so much!

,

This is because Rails 3 changed the way it uses javascript in forms. It used to add an onclick method to the link, but that goes against unobtrusive javascript. Now it just sets some tag attributes, and hooks into it with javascript in another file.

That page’s layout (which is probably application.html.erb unless you’ve changed it) needs to have this line in the head section:

<%= javascript_include_tag :defaults %>

If this line is missing from your layout, that’s the problem. Another possible cause could be if you’ve added the jQuery library to your app without adding the rails-specific jQuery library. Let me know how this works.

,

This may help you link_to with :method=>:delete not working ( Rails 3 ). Although in that article the edit is getting called instead. But the solution should work for show as well.

Leave a Comment