Created
July 22, 2018 14:43
-
-
Save Innarticles/2de2f42fa9db1b8cd6d653408dfdba09 to your computer and use it in GitHub Desktop.
Rails Code Snippet on Creating Objects from CSV data
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
csv_text = File.read(Rails.root.join('lib', 'seeds', 'products.csv')) | |
csv = CSV.parse(csv_text, :headers => true, :encoding => 'ISO-8859-1') | |
csv.each do |row| | |
t = Product.new | |
t.id = row['id'] | |
t.title = row['title'] | |
t.brand = row['brand'] | |
t.description = row['description'] | |
t.main_image = row['picture'] | |
t.condition = row['condition'] | |
t.category = row['category'] | |
t.style = row['style'] | |
t.price = row['price'] | |
t.retail_price = row['retailprice'] | |
t.sale_price = row['sale price'] | |
t.is_on_sale = row['is on sale'] | |
t.user_id = row['user'] | |
t.created_at = row['created_at'] | |
t.updated_at = row['updated_at'] | |
t.approved_at = row['approved_at'] | |
t.size = row['size'] | |
t.color = row['color'] | |
t.wear_tags = row['wear_tags'] | |
t.images = row[''] | |
t.sold_at=row['sold_at'] | |
t.slug=row[''] | |
t.save | |
puts "#{t.street}, #{t.city} saved" | |
end | |
puts "There are now #{Product.count} rows in the products table" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment