views:

27

answers:

2

I have a model called NoteCategory, which is functioning as a join table between Notes and Categories.

Up till this point, I have used scaffolding to do everything in RoR. I'm trying to learn how to do some stuff more manually.

I want to have a link that will appear next to each category on a note, that will remove the category from the note. So I need to create a route that will delete the entry from the join table.

So far I have created a controller

class NoteCategoriesController < ApplicationController
    def destroy
      notecategory = NoteCategory.find(params[:id])
      notecategory.destroy
      respond_to do |format|
        format.html { redirect_to(notes_url) }
        format.xml  { head :ok }
      end
    end
end

I then added this line to routes.db

map.resources :note_categories

And here is the link in the view:

<%= button_to 'Delete', :confirm => 'Are you sure?', :controller => "notecategories",:action => :destroy %>

When I click the button, I get this error message:

No route matches "/notecategories/destroy" with {:method=>:post}

What am I doing wrong? Thanks for reading.

A: 

try:

<%= button_to 'Delete', :confirm => 'Are you sure?', :controller => "notecategories",:action => :destroy, :method => :delete %>

Note the :method

It's because of the RESTful routes use those PUT, DELETE, POST, etc action words with together the paths (ie. /notecategories/destroy with :delete together for destroying records)

PeterWong
+1  A: 

map.resources doesn't create /$controller/destroy route. Run rake routes and see what exactly you have.

As for having it right, this 'delete' button is generated by scaffold command for simple CRUD application, so it should work.

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

edit
Whole 'index.html.erb' page generated by 'scaffold' command. It should give you general idea.

<h1>Listing events</h1>

<table>
  <tr>
    <th>Name</th>
    <th>Budget</th>
  </tr>

<% @events.each do |event| %>
  <tr>
    <td><%=h event.name %></td>
    <td><%=h event.budget %></td>
    <td><%= link_to 'Show', event %></td>
    <td><%= link_to 'Edit', edit_event_path(event) %></td>
    <td><%= link_to 'Destroy', event, :confirm => 'Are you sure?', :method => :delete %></td>
  </tr>
<% end %>
</table>

<br />

<%= link_to 'New event', new_event_path %>
Nikita Rybak
I didn't used the `event` before, could you tell me more about that? Thanks!
PeterWong
@PeterWong It's an object you want to destroy. I just've taken example from page generated for "Event" model by "script/generate scaffold event name:string".
Nikita Rybak
@Nikita Rybak Ooops, sorry for missing the declaration line. :D
PeterWong