Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
like image 964
John Avatar asked Dec 12 '13 00:12

John


1 Answers

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!.

like image 92
OneChillDude Avatar answered Oct 09 '22 05:10

OneChillDude