我正在将包含数百行的 CSV 导入我的 rails 数据库。
有时用户想强制覆盖数据,所以我认为最好销毁所有数据并重新开始。
就像是:
account.catalog_listings.delete_all if should_refresh
CSV.foreach(file, options) do |row|
account.catalog_listings.create!({...rowstuff})
问题是该delete_all
行正在引发 PG 错误
ActiveRecord::StatementInvalid (PG::NotNullViolation: ERROR: null value in column "account_id" violates not-null constraint
DETAIL: Failing row contains (1, null, ... ... ).
: UPDATE "catalog_listings" SET "account_id" = NULL WHERE "catalog_listings"."account_id" = $1):
app/models/catalog_listing.rb:41:in `import_catalog_listings'
app/controllers/accounts_controller.rb:20:in `catalog'
我确实有null: false
几个外键字段,但我不知道为什么delete_all
要尝试删除外键而不是删除整个记录?
更新 - 当我改变时一切正常:
account.catalog_listings.delete_all if should_refresh
至:
account.catalog_listings.destroy_all if should_refresh
除了destroy
遍历每个项目并逐个删除:
SQL (0.1ms) DELETE FROM "catalog_listings" WHERE "catalog_listings"."id" = $1 [["id", 957]]
SQL (0.1ms) DELETE FROM "catalog_listings" WHERE "catalog_listings"."id" = $1 [["id", 958]]
SQL (0.1ms) DELETE FROM "catalog_listings" WHERE "catalog_listings"."id" = $1 [["id", 959]]
SQL (0.1ms) DELETE FROM "catalog_listings" WHERE "catalog_listings"."id" = $1 [["id", 960]]
SQL (0.1ms) DELETE FROM "catalog_listings" WHERE "catalog_listings"."id" = $1 [["id", 961]]
SQL (0.1ms) DELETE FROM "catalog_listings" WHERE "catalog_listings"."id" = $1 [["id", 962]]
SQL (0.2ms) DELETE FROM "catalog_listings" WHERE "catalog_listings"."id" = $1 [["id", 963]]
SQL (0.2ms) DELETE FROM "catalog_listings" WHERE "catalog_listings"."id" = $1 [["id", 964]]
SQL (0.2ms) DELETE FROM "catalog_listings" WHERE "catalog_listings"."id" = $1 [["id", 965]]
SQL (0.2ms) DELETE FROM "catalog_listings" WHERE "catalog_listings"."id" = $1 [["id", 966]]
SQL (0.3ms) DELETE FROM "catalog_listings" WHERE "catalog_listings"."id" = $1 [["id", 967]]
SQL (0.2ms) DELETE FROM "catalog_listings" WHERE "catalog_listings"."id" = $1 [["id", 968]]
SQL (0.2ms) DELETE FROM "catalog_listings" WHERE "catalog_listings"."id" = $1 [["id", 969]]
SQL (0.2ms) DELETE FROM "catalog_listings" WHERE "catalog_listings"."id" = $1 [["id", 970]]
SQL (0.2ms) DELETE FROM "catalog_listings" WHERE "catalog_listings"."id" = $1 [["id", 971]]
SQL (0.2ms) DELETE FROM "catalog_listings" WHERE "catalog_listings"."id" = $1 [["id", 972]]
SQL (0.2ms) DELETE FROM "catalog_listings" WHERE "catalog_listings"."id" = $1 [["id", 973]]
SQL (0.3ms) DELETE FROM "catalog_listings" WHERE "catalog_listings"."id" = $1 [["id", 974]]
SQL (0.2ms) DELETE FROM "catalog_listings" WHERE "catalog_listings"."id" = $1 [["id", 975]]
不酷...有人知道更好的方法吗?