即使无法保存 1 条记录,使 seeds.rb 文件继续播种

Make seeds.rb file continue to seed even when 1 record couldn't be saved

我有一个 seeds.rb 可以为我的数据库播种。

当我 运行 它时,我得到这个错误:

$ rake db:seed

rake aborted!
ActiveRecord::StatementInvalid: PG::StringDataRightTruncation: ERROR:  value too long for type character varying(255)
: INSERT INTO "jobs" ("name", "location", "industry", "description") VALUES (, , , ) RETURNING "id"

显然 string 列的值太长。

而不是将 string 列更改为 text,我如何更改我的 seeds.rb 文件或任何其他内容(可能是验证)以不将此行插入数据库并继续在?

seeds.rb

Job.create([
  {name: "foo", location: "indiana", industry: "cooking", description: "Making lobster all day biznatch"},
  {name: "booz", location: "kentucky", industry: "chicken_mining", description: "We mine mad chickens so you can eat derrish KFC."},
  ...
])

如果您使用 #create 而不是 #create!ActiveRecord 将不会在验证错误的情况下引发。事实上,如果没有创建记录,#create returns false。

但是,您的情况有点不同。失败的原因不是 ActiveRecord 验证错误(在 bang 方法的情况下会引发 ActiveRecord::RecordInvalid),而是数据库级错误。更具体地说,这是引发 ActiveRecord::StatementInvalid.

的约束违规

这种异常无法绕过,即使你使用非bang版本,因为ActiveRecord认为它是低级故障。

有几种可能的解决方案。首先,可以对每条记录进行一条一条的创建,拯救RuntimeError(s).

attributes = [
  {name: "foo", location: "indiana", industry: "cooking", description: "Making lobster all day biznatch"},
  {name: "booz", location: "kentucky", industry: "chicken_mining", description: "We mine mad chickens so you can eat derrish KFC."},
  ...
]

attributes.each do |params|
  begin
    Job.create(params)
  rescue => e
    puts "Error #{e.message} with params #{params}"
  end
end

此外,您可以在 ActiveRecord 模型中的字段上添加大小验证,以确保内容将被预先验证并且 ActiveRecord 不会尝试创建和执行无效的 SQL 语句。

一般来说,这种错误应该被认为是你代码中的一个错误,你真的不想让它消失。这就是为什么即使你使用非 bang create 版本,ActiveRecord 也会报错。

您向数据库引擎传递了一些无效数据,除非您准备好承担风险(并处理异常),否则不应发生这种情况。