PG :: ForeignKeyViolation:ERROR:表上的插入或更新违反了外键约束

时间:2016-10-20 00:12:16

标签: ruby-on-rails postgresql

我已经将我的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

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不在products表中,但它是。如果我在products表上的sku上运行SQL查询,则返回一行。

我有什么问题?

1 个答案:

答案 0 :(得分:4)

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