Last active
January 1, 2016 19:59
-
-
Save guinslym/8193851 to your computer and use it in GitHub Desktop.
wrong number of arguments (3 for 2) for when ".csv" then Roo::Csv.new(file.path, nil, :ignore)
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
class Product < ActiveRecord::Base | |
require 'roo' | |
validates_presence_of :price | |
def self.to_csv(options = {}) | |
CSV.generate(options) do |csv| | |
csv << column_names | |
all.each do |product| | |
csv << product.attributes.values_at(*column_names) | |
end | |
end | |
end | |
def self.import(file) | |
spreadsheet = open_spreadsheet(file) | |
header = spreadsheet.row(1) | |
(2..spreadsheet.last_row).each do |i| | |
row = Hash[[header, spreadsheet.row(i)].transpose] | |
product = find_by_id(row["id"]) || new | |
product.attributes = row.to_hash.slice(*accessible_attributes) | |
product.save! | |
end | |
end | |
def self.open_spreadsheet(file) | |
case File.extname(file.original_filename) | |
when ".csv" then Roo::Csv.new(file.path, nil, :ignore) | |
when ".xls" then Roo::Excel.new(file.path, nil, :ignore) | |
when ".xlsx" then Roo::Excelx.new(file.path, nil, :ignore) | |
else raise "Unknown file type: #{file.original_filename}" | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Importing Excel Spreadsheets using Roo
Limitation has mentioned.
http://railscasts.com/episodes/396-importing-csv-and-excel?view=asciicast
Read below lines from above link...
" This works. The list now contains the new products from the Excel document. One issue with this solution is that it doesn’t like to import any files that we export from our application: an exception is raised when we try it. Files generated by Excel seem to import without any problems, however. "