Reputation: 1017
I have a ruby app where I have a documents model. Documents can be added to a cart for download. Once the cart is downloaded the items in the cart can be wiped out and the cart deleted. I am running into a problem when I try to destroy a document. I'm getting
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(version: 20160119182713) do
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
This is running on a microsoft SQL server database but I don't think it is a constraint issue. My main question is if my models are correct to allow the deletion of a document. I don't care if that wipes out the associated items. Once the documents are downloaded, the cart and associated items are no longer used.
Upvotes: 1
Views: 756
Reputation: 6438
has_and_belongs_to_many relationship expects the join table be created as part of the migration. In your case, you are missing creation of 'carts_documents' in your migration.
Visit Active Record Associations and Active Record API for more info
Upvotes: 1