Skip to content

Instantly share code, notes, and snippets.

@raecoo
Forked from bcalloway/create_imports.rb
Created December 10, 2013 02:01
Show Gist options
  • Save raecoo/7884667 to your computer and use it in GitHub Desktop.
Save raecoo/7884667 to your computer and use it in GitHub Desktop.
class CreateImports < ActiveRecord::Migration
def self.up
create_table :imports do |t|
t.string :datatype
t.integer :processed, :default => 0
t.string :csv_file_name
t.string :csv_content_type
t.integer :csv_file_size
t.timestamps
end
end
def self.down
drop_table :imports
end
end
class Import < ActiveRecord::Base
has_attached_file :csv,
:url => "#{RAILS_ROOT}/:basename.:extension",
:path => ":rails_root/:basename.:extension"
validates_attachment_presence :csv
validates_attachment_content_type :csv, :content_type => ['text/csv','text/comma-separated-values','text/csv','application/csv','application/excel','application/vnd.ms-excel','application/vnd.msexcel','text/anytext','text/plain']
end
class ImportsController < ApplicationController
def new
@import = Import.new
end
def create
@import = Import.new(params[:import])
respond_to do |format|
if @import.save!
self.import_inventory
flash[:notice] = 'Inventory was successfully imported.'
format.html { redirect_to('/products') }
else
flash[:error] = 'Inventory data import failed.'
format.html { render :action => "new" }
end
end
end
def import_inventory
@import = Import.last
FasterCSV.foreach("#{@import.csv.path}") do |row|
record = Product.new(
:sku => row[0],
:category_id => row[1],
:name => row[2],
:price => row[3],
:created_at => Time.now,
:updated_at => Time.now
)
record.save
end
end
end
- semantic_form_for Import.new, :html => { :multipart => true } do |f|
- f.inputs do
= f.input :csv, :as => :file, :hint => "Only TXT or CSV formats allowed.", :label => "Upload Inventory"
= f.commit_button "Upload"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment