2

我不断收到此错误,但在此处找不到解决此错误的答案。

我有一个 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" 
4

2 回答 2

2

我有同样的错误,但出于不同的原因。我在这里发布作为答案,以防其他人遇到此问题。就我而言,问题是我使用的控制器与我试图删除的模型行不同。我正在使用用户控制器删除结帐。有趣的是,我可以使用以下代码从第三个模型(课程)中删除一行:

<%= 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 强迫我使用正确的控制器的方式。

于 2014-09-04T19:43:58.123 回答
1

改变你likes_path(like.id)like_path(like)享受:)

于 2013-05-10T00:51:22.050 回答