【问题标题】:Run a rake db:seed multiple times without creating duplicate records? [duplicate]多次运行 rake db:seed 而不创建重复记录? [复制]
【发布时间】:2013-12-30 05:38:32
【问题描述】:

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

【问题讨论】:

  • 为什么你认为find_or_create_by 在这里行不通?

标签: ruby-on-rails ruby database postgresql seeding


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多