Skip to content

Instantly share code, notes, and snippets.

@diatmpravin
Created January 22, 2013 17:54
Show Gist options
  • Save diatmpravin/4596654 to your computer and use it in GitHub Desktop.
Save diatmpravin/4596654 to your computer and use it in GitHub Desktop.
multi-table-ex
class User < ActiveRecord::Base
attr_accessible :fname, :lname
has_many :parents, :dependent => :destroy
def self.export_to_csv(filename, model, options = {})
csv_options = {}
csv_options[:col_sep] = options[:separator] || ','
header = User.header(model,options = {})
data = User.data(model)
coll = CSV.generate(csv_options) do |csv|
csv << header
row = Array.new
#raise data.inspect
#raise header.inspect
data.each do |obj|
header.each do |col|
row << obj
end
csv << row
row.clear
end
#raise header.count.inspect
#header.count.times do
# data.each do |obj|
# row << obj[col]
# csv << row
# row.clear
# end
#end
end
return coll,filename,'text/csv'
# send_data(data, :filename => filename,:type => 'text/csv')
end
def self.header(model, options = {})
header = Array.new
model.each do |e_model|
model_dir = Dir['**/models/**/*.rb'].detect {|f| e_model == File.basename(f, '.*').camelize}
if !model_dir.eql?(nil)
table = File.basename(model_dir, '.*').camelize.constantize
header.concat(table.column_names)
else
puts "Table #{ENV['model']} could not be found"
end
end
return header
end
def self.data(model)
data = Array.new
model.each do |e_model|
model_dir = Dir['**/models/**/*.rb'].detect {|f| e_model == File.basename(f, '.*').camelize}
table = File.basename(model_dir, '.*').camelize.constantize
objects = table.all
#raise objects.inspect
row = Array.new
objects.each do |obj|
table.column_names.each do |col|
row << obj[col]
end
data.concat(row)
row.clear
end
end
return data
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment