1
我已經更新了我的Rails應用程序從SQLite到Postgres,當我嘗試添加新產品庫存時出現以下錯誤:PG :: ForeignKeyViolation:錯誤:在表上插入或更新違反外鍵約束
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
Stock.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查詢,它將返回一行。
我有什麼問題?
你從哪裏得到'16819'的sku?你是如何特別知道它是有效的?你確定你正在對同一個數據庫運行SQL查詢嗎? –
sku來自我自己添加的產品。它在db中,因爲我可以用'Product.find_by(sku:16819)'' – Yotops
'檢索它。你可以使用SKU從'Product.find_by(sku:16819)'工作的同一個控制檯創建'Stock'嗎? –