7

我在种子文件中有一些我想更改的代码,以便在我多次运行种子命令时它不会创建重复记录。有什么方法可以从我的种子文件中修改下面的代码,这样就可以了?除非我弄错了,否则 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
4

1 回答 1

7

使用验证。如果您不想重复记录,请验证一个或多个字段的唯一性。在你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

另一方面,不,.create!会引发错误。.create将不会。save!和 也是如此.update_attributes!

于 2013-12-12T00:46:00.017 回答