Shikasan
Shikasan

Reputation: 329

No route matches [DELETE] "/models.id" Error

I keep getting this error and I haven't found an answer here that addresses this error.

I have a Book, User and Like model stated like this:

class Book < ActiveRecord::Base
  attr_accessible :title

  has_many :likes
  has_many :users, through: :likes
end

class User < ActiveRecord::Base
  attr_accessible :name

  has_many :likes
  has_many :books, through: :likes
end

class Like < ActiveRecord::Base
  attr_accessible :book, :user

  belongs_to :book
  belongs_to :user
end

Corresponding likes controllers:

# app/controllers/likes_controller.rb
class LikesController < ApplicationController

  def index
    # Assign the logged in user to @user
    @user = current_user
    # Grab all of the books and put them into an array in @books
    @books = Book.all
  end

  def create 
    book = Book.find(params[:book_id])
    Like.create(:book => book, :user => current_user)
    redirect_to likes_path, :notice => "You just liked the book #{book.title}" 
  end

  def destroy
    like = Like.find(params[:id])
    like.destroy
    redirect_to likes_path, :notice => "You destroyed a like"
  end
end

In my config/routers.rb:

MyApp::Application.routes.draw do

  resources :likes

 end

I have link that is supposed to delete an existing like:

<% like = book.likes.where(:user_id => @user.id).first %>
 <%= link_to "destroy like", likes_path(like.id), :method => :delete %

But when I click the link, I get this error:

No route matches [DELETE] "/likes.7" 

Upvotes: 2

Views: 4176

Answers (2)

Chemist
Chemist

Reputation: 966

I had the same error but for a different reason. I'm posting here as an answer in case someone else runs into this. In my case the problem was that I was using different controller than the model row I was trying to delete. I was using Users controller to delete a Checkout. Interestingly, I was able to delete a row from a third model (Course) with this code:

<%= link_to 'Delete', c.course, method: :delete, data: { confirm: 'Are you sure?' } %>

but this did not work (and threw the error No route matches [DELETE] "/checkouts.7")

<%= link_to 'Delete', c, method: :delete, data: { confirm: 'Are you sure?' } %>

The error was resolved when I moved code to use CheckoutsController and the associated view instead of UsersController. Must be Rails' way of forcing me to use the right controller.

Upvotes: 2

pungoyal
pungoyal

Reputation: 1798

Change your likes_path(like.id) to like_path(like) and enjoy :)

Upvotes: 1

Related Questions