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
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!
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With