多次运行rake db:seed而不创建重复记录?

Joh*_*ohn 7 ruby database postgresql ruby-on-rails seeding

我在种子文件中有一些代码,我想改变它,以便在我多次运行种子命令时不会创建重复的记录.有没有办法从我的种子文件中调整下面的代码,以便这可能?除非我弄错了,否则find_or_create_by方法似乎不起作用.

data_file = Rails.root.join('db/data/data.csv')

CSV.foreach(data_file) do |row|
  TownHealthRecord.create(
    city: row[0],
    state: row[1],
    country: row[2],
    zip_code: row[3],
    area_code: row[4]
    )
end
Run Code Online (Sandbox Code Playgroud)

One*_*ude 6

使用验证.如果您不想要重复记录,请验证一个或多个字段的唯一性.在你身上town_health_record.rb

class TownHealthRecord
  validates_uniqueness_of :city
  validates uniqueness_of :health, scope: :person # If you wanted to validate a combination of fields
end
Run Code Online (Sandbox Code Playgroud)

另外一方面,.create!不会引发错误..create将不会.这同样适用于save!.update_attributes!.