gpt4 book ai didi

ruby-on-rails - ActiveRecord::InvalidForeignKey 错误

转载 作者:太空宇宙 更新时间:2023-11-03 18:06:33 24 4
gpt4 key购买 nike

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

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

最佳答案

听起来好像有一个从另一个表到 inventory 表的外键,您希望在 Inventory 模型中看到它以 has_manyhas_one 关系表示.

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

前者会非常快,但不允许在子实例上执行回调,所以我建议使用 :destroy 选项。

关于ruby-on-rails - ActiveRecord::InvalidForeignKey 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44164900/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com