Last active
October 5, 2015 18:45
-
-
Save hendricius/3aa10e4f4b7c2b5c9f62 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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