Skip to content

Instantly share code, notes, and snippets.

@hendricius
Last active October 5, 2015 18:45
Show Gist options
  • Save hendricius/3aa10e4f4b7c2b5c9f62 to your computer and use it in GitHub Desktop.
Save hendricius/3aa10e4f4b7c2b5c9f62 to your computer and use it in GitHub Desktop.
namespace :db do
desc "Populate database"
task :populate => :environment do
[Brand].each(&:delete_all)
filename = File.join Rails.root, "databases/brands.csv"
counter = 0
CSV.foreach(filename, headers: true) do |row|
p row
brand = Brand.create!(id: row["id"], brandname: row["brandname"])
counter += 1
end
puts "Imported #{counter} brands"
end
end
model:
class Brand < ActiveRecord::Base
validates :brandname, uniqueness: true
# validates :brandname, uniqueness: { scope: :brandname } - in case you need it scoped
end
# also create a uniquenuess constraint in the database if needed
class MyMigration
def change
add_index :brands, :brandname, unique: true, null: false
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment