To Create CSV file in Rails:
@models = Model.find(:all, :conditions => ['...'])
rawdata = StringIO.new
CSV::Writer.generate(rawdata, ',') do |csv|
csv << %w(Title Total)
@models.each do |model|
csv << [model.title, model.total]
:type => 'text/csv; charset=iso-8859-1; header=present',
:filename => 'rawdata.csv')
To retrieve, here is the lib…
FasterCSV is intended as a
replacement to Ruby‘s standard CSV library. It was designed to
address concerns users of that library had and it has three primary goals:
- Be significantly faster than CSV while remaining a pure Ruby library.
- Use a smaller and easier to maintain code base. (FasterCSV is larger now, but
considerably richer in features. The parsing core remains quite small.)
- Improve on the CSV interface.
def retrieve_csv csv_file = params[:csv_file]
fastercsv = FasterCSV.new( csv_file )
while row = fastercsv.readline
foo, bar = row
Record.create!( :foo => foo, :bar => bar )
# do something with the error
flash[:error] = "CSV import failed"