没有路由匹配[DELETE]“/ models.id”错误

时间:2013-05-10 00:01:27

标签: ruby-on-rails-3 ruby-on-rails-3.2 routes

我一直收到此错误,但我没有找到解决此错误的答案。

我有一本Book,User和Like模型,如下所示:

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

对应喜欢的控制器:

# 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

在我的config / routers.rb中:

MyApp::Application.routes.draw do

  resources :likes

 end

我有链接应该删除现有的:

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

但是当我点击链接时,我收到此错误:

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

2 个答案:

答案 0 :(得分:2)

我有同样的错误,但原因不同。我在这里发帖作为答案,以防其他人遇到此问题。在我的情况下,问题是我使用不同的控制器而不是我试图删除的模型行。我正在使用Users控制器删除Checkout。有趣的是,我能够使用以下代码从第三个模型(课程)中删除一行:

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

但这不起作用(并抛出错误No route matches [DELETE] "/checkouts.7"

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

当我移动代码以使用CheckoutsController和关联的视图而不是UsersController时,错误得到了解决。必须是Rails&#39;迫使我使用正确的控制器的方法。

答案 1 :(得分:1)

将您的likes_path(like.id)更改为like_path(like)并享受:)