Rails删除记录失败

时间:2016-02-05 19:56:38

标签: ruby-on-rails

我有一个ruby应用程序,我有一个文档模型。可以将文档添加到购物车中以供下载。下载购物车后,可以清除购物车中的商品并删除购物车。我试图销毁文档时遇到问题。我得到了

ActiveRecord::StatementInvalid in DocumentsController#destroy
TinyTds::Error: Invalid object name 'tl.carts_documents'.: EXEC sp_executesql N'DELETE FROM [tl].[carts_documents] WHERE [tl].[carts_documents].[document_id] = @0; SELECT @@ROWCOUNT AS AffectedRows', N'@0 int', @0 = 3

Rails.root: C:/Users/cmendla/RubymineProjects/technical_library

Application Trace | Framework Trace | Full Trace
app/controllers/documents_controller.rb:150:in `destroy'
Request

Parameters:

{"_method"=>"delete",
 "authenticity_token"=>"T0JBA. . . 3Q==",
 "id"=>"3"}

class Document < ActiveRecord::Base

  belongs_to :category, :class_name => 'Category', :foreign_key => 'category_id'
 # belongs_to :owner, :class_name => 'Owner', :foreign_key => 'owner_id'
  has_and_belongs_to_many :carts, :dependent => :destroy
  accepts_nested_attributes_for :carts

class Cart < ActiveRecord::Base

  has_and_belongs_to_many :documents
  has_many :items, :dependent => :destroy
  accepts_nested_attributes_for :items

class Item < ActiveRecord::Base
  belongs_to :cart
end

。     ActiveRecord :: Schema.define(版本:20160119182713)做

  create_table "carts", force: :cascade do |t|
    t.string   "user"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end


  create_table "documents", force: :cascade do |t|
    t.string   "document_title"
    t.text     "summary"
    t.integer  "owner_id"
    t.integer  "category_id"
    t.datetime "created_at",            null: false
    t.datetime "updated_at",            null: false
    t.string   "doc_file_file_name"
    t.string   "doc_file_content_type"
    t.integer  "doc_file_file_size"
    t.datetime "doc_file_updated_at"
    t.string   "owner_index"
    t.string   "category_index"
  end

  create_table "items", force: :cascade do |t|
    t.integer  "document_id"
    t.string   "user"
    t.integer  "cart_id"
    t.datetime "created_at",  null: false
    t.datetime "updated_at",  null: false
  end

  add_index "items", ["cart_id"], name: "index_items_on_cart_id"

def destroy




    @document.destroy
    respond_to do |format|
      format.html { redirect_to documents_url, notice: 'Document was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

这是在Microsoft SQL Server数据库上运行,但我不认为这是一个约束问题。我的主要问题是我的模型是否正确以允许删除文档。我不在乎是否擦掉了相关的物品。下载文档后,不再使用购物车和相关项目。

1 个答案:

答案 0 :(得分:1)

has_and_belongs_to_many 关系期望在迁移过程中创建连接表。在您的情况下,您缺少&#39; carts_documents&#39;在您的迁移中。

访问Active Record AssociationsActive Record API了解详情