Run a rake db:seed multiple times without creating duplicate records? [duplicate]
Asked Answered
T

1

7

I have some code in a seed file that I'd like to alter so that it does not create duplicate records when I run the seed command multiple times. Any way to adapt the code below from my seeds file so that this is possible? The find_or_create_by method doesn't appear to work here unless I am mistaken.

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
Tshirt answered 12/12, 2013 at 0:36 Comment(1)
why do you think find_or_create_by won't work here?Linotype
N
7

Use a validation. If you don't want duplicate records, validate the uniqueness of one or more fields. In you 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

On an added side not, .create! will raise errors. .create will not. Same goes for save! and .update_attributes!.

Neel answered 12/12, 2013 at 0:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.