gpt4 book ai didi

ruby-on-rails - PG::ForeignKeyViolation: 错误:在表上插入或更新违反了外键约束

转载 作者:行者123 更新时间:2023-11-29 12:36:15 26 4
gpt4 key购买 nike

我已将我的 Rails 应用程序从 SQLite 更新到 Postgres,当我尝试添加新产品库存时出现以下错误:

ActiveRecord::InvalidForeignKey: PG::ForeignKeyViolation: ERROR:  insert or update on table "stocks" violates foreign key constraint "fk_rails_6d8dd2a287"
DETAIL: Key (sku)=(16819) is not present in table "products".
: INSERT INTO "stocks" ("store_code", "sku", "quantity", "date", "created_at", "updated_at") VALUES ($1, $2, $3, $4, $5, $6) RETURNING "id"

Store.rb

class Store < ApplicationRecord
has_many :stocks, -> { group(:sku) }, foreign_key: :store_code, primary_key: :store_code
has_many :products, through: :stocks
end

Product.rb

class Product < ApplicationRecord
has_many :stocks, -> { group(:store_code) }, foreign_key: :sku, primary_key: :sku
has_many :stores, through: :stocks
end

股票.rb

class Stock < ApplicationRecord
belongs_to :store, primary_key: :store_code, foreign_key: :store_code, class_name: 'Store'
belongs_to :product, primary_key: :sku, foreign_key: :sku, class_name: 'Product'
end

我的迁移是:

class CreateStores < ActiveRecord::Migration[5.0]
def change
create_table :stores do |t|
t.integer :store_code, null: false
t.string :name
t.string :address

t.timestamps
end
add_index :stores, :store_code, unique: true
end
end

class CreateProducts < ActiveRecord::Migration[5.0]
def change
create_table :products do |t|
t.integer :sku, null: false
t.string :product_type
t.string :name
t.decimal :price, precision: 15, scale: 2
t.integer :volume
t.decimal :abv, precision: 3, scale: 1
t.integer :sweetness
t.string :style
t.string :country
t.string :region
t.integer :year
t.text :notes

t.timestamps
end
add_index :products, :sku, unique: true
end
end

class CreateStocks < ActiveRecord::Migration[5.0]
def change
create_table :stocks do |t|
t.integer :store_code, index: true
t.integer :sku, index: true
t.integer :quantity
t.date :date, index: true

t.timestamps
end
add_foreign_key :stocks, :stores, column: :store_code
add_foreign_key :stocks, :products, column: :sku
end
end

错误是说 sku 不在产品表中,但它在。如果我在产品表的那个 sku 上运行 SQL 查询,它会返回一行。

我做错了什么?

最佳答案

因此,通过重新启动并重置所有内容来解决问题。我重新启动了 postgres,退出了服务器和控制台,运行了 rake db:migrate:reset,现在我可以毫无问题地插入股票了。

关于ruby-on-rails - PG::ForeignKeyViolation: 错误:在表上插入或更新违反了外键约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40143485/

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