开发者

What is wrong with this attempt to create a route to delete a record in RoR?

开发者 https://www.devze.com 2023-01-12 11:47 出处:网络
I have a model called NoteCategory, which is functioning as a join table between Notes and Categories.

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.


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


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)

0

精彩评论

暂无评论...
验证码 换一张
取 消