2017-05-24 67 views
0

當我嘗試從我的庫存數據庫中刪除的東西,我得到這個錯誤:的ActiveRecord :: InvalidForeignKey錯誤

ActiveRecord::InvalidForeignKey in InventoriesController#destroy 

SQLite3::ConstraintException: FOREIGN KEY constraint failed: DELETE FROM "inventories" WHERE "inventories"."id" = ? 

在終端,它說

{"_method"=>"delete", "authenticity_token"=>"dBNU2GkV0+rOcp4NVEljm4oIpkdOnPsvZKdmisaadBzX3QkY1VwurZNRPL0WFtVvizeAcJb7H6E50ObmpRsXAg==", "id"=>"1"} 

還說源是在:

def destroy 
    @inventory = Inventory.find(params[:id]) 
    @inventory.destroy 

    redirect_to inventory_path 
end 

在我的庫存文件,該文件是:

class InventoriesController < ApplicationController 
    def show 
     @inventory = Inventory.find(params[:id]) 
    end 

    def index 
     @inventories = Inventory.all 
    end 

    def new 
     @inventory = Inventory.new 
    end 

    def create 
     @inventory = Inventory.new(inventory_params) 


     if @inventory.save 
     redirect_to @inventory 
     else 
      render 'new' 
     end 
    end 

    def edit 
     @inventory = Inventory.find(params[:id]) 
    end 

    def update 
     @inventory = Inventory.find(params[:id]) 
     if @inventory.update(inventory_params) 
      redirect_to @inventory 
     else 
      render 'edit' 
     end 
    end 

    def destroy 
     @inventory = Inventory.find(params[:id]) 
     @inventory.destroy 

     redirect_to inventory_path 
    end 
end 

private 
def inventory_params 
    params.require(:inventory).permit(:product_name, :brand_name, :item_id, :upc_code, :color, :department, :size, :condition, :fabric_type, :shipping_weight, :sku, :asin, :quantity, :cost_price, :sell_price, :key_product_features, :product_description, :search_terms, :status, :listing_in_usa, :listing_in_canada, :listing_in_mexico) 

end 
+0

'Inventory'和'Item'之間有關係,你需要處理這個和/或在你的關係中指定'destroy''依賴關係。 –

回答

1

這聽起來像有一個從另外一個,你會希望看到與has_manyhas_one關係的庫存模型表示的外鍵的庫存表。

修復方法是將外鍵配置爲自動刪除子記錄或在關聯上指定dependent: :destroy

前者會非常快,但不會允許執行子實例的回調,所以我建議使用:destroy選項。

相關問題