ActiveRecord :: InvalidForeignKey错误

时间:2017-05-24 17:18:41

标签: ruby-on-rails ruby activerecord

当我尝试从库存数据库中删除某些内容时,出现此错误:

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

1 个答案:

答案 0 :(得分:1)

听起来,另一个库存表中有一个外键,您可以在库存模型中看到它与has_manyhas_one的关系。

修复方法是将外键配置为自动删除子记录,或者在关联上指定dependent: :destroy

前者速度非常快,但不允许执行子实例的回调,因此我建议使用:destroy选项。