Skip to content

Instantly share code, notes, and snippets.

@postpostmodern
Created March 20, 2012 14:38
Show Gist options
  • Save postpostmodern/2136288 to your computer and use it in GitHub Desktop.
Save postpostmodern/2136288 to your computer and use it in GitHub Desktop.
Example seeds.rb file which creates records and imports records from CSV files
Language.create!(name: 'English (US)', code: 'en', locale: 'en-US') if Language.count == 0
if Administrator.count == 0
admin = Administrator.new(
first_name: 'Super',
last_name: 'Admin',
email: 'admin@example.com',
password: 'adminpass',
password_confirmation: 'adminpass'
)
admin.hidden = true
admin.confirmed_at = Time.now
admin.save!
end
ActiveRecord::Base.transaction do
if FilterCollectionLocation.count == 0
CSV.foreach(File.join(Rails.root, "db", "seed_data", "filter_collection_companies.csv"), :headers => true, :encoding => 'UTF-8') do |row|
row = row.to_hash
if company = FilterCollectionCompany.find_or_create_by_name(row['name'])
company.update_attribute(:website, row['website'])
puts "Created #{company.name}."
else
puts "COULD NOT CREATE #{row['name']}!"
end
end
CSV.foreach(File.join(Rails.root, "db", "seed_data", "filter_collection_locations.csv"), :headers => true, :encoding => 'UTF-8') do |row|
row = row.to_hash.merge({ nora: true })
if (company = FilterCollectionCompany.find_or_create_by_name(row.delete('company'))) && (company_location = company.filter_collection_locations.create(row))
puts "Created #{company_location.city} location for #{company.name}."
else
puts "COULD NOT CREATE #{row['city']} location for #{row['company']}!"
end
end
end
end
@greyblake
Copy link

You can use fast_seeder(https://github.com/greyblake/fast_seeder) as well. It support number of DB adapters.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment