我正在将几百行的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'
我 DO 在几个外键字段上有一个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]]
不酷......任何人都知道更好的方法吗?
答案 0 :(得分:2)
尝试在dependent: :destroy
模型的catalog_listings
关联中添加Account
。
https://apidock.com/rails/ActiveRecord/Associations/CollectionProxy/delete_all