Skip to content

Instantly share code, notes, and snippets.

@aantix
Created January 1, 2011 02:34
Show Gist options
  • Save aantix/761513 to your computer and use it in GitHub Desktop.
Save aantix/761513 to your computer and use it in GitHub Desktop.
Display model data in hash form for create -- Useful in dumping old Rails model data (for seeds.rb)
model = Object::const_get(ARGV[0])
rows = model.find(:all)
# Any columns you don't want output, list here as symbols
# e.g. BLACKLIST = [:user_id, :workout_id]
BLACKLIST = []
# Any columns that you'd like to rename on the output, list in this hash
# e.g. TRANSFORM = {:percentOfMax => :percent_of_max}
TRANSFORM = {}
rows.each do |r|
sql = "#{model.to_s}.create({"
vals = []
model.column_names.each do |c|
col = c.to_sym
next if BLACKLIST.include?(col)
val = r.send(c.to_sym)
c = TRANSFORM[col] if TRANSFORM[col]
case val.class.to_s
when 'NilClass' then vals << ":#{c} => nil"
when 'String' then vals << ":#{c} => '#{val}'"
else
vals << ":#{c} => #{val}"
end
end
sql+=vals[1..vals.size].join(',')
sql+= "}) "
sql+="{|ar| ar.id = #{r.send(:id)}; ar.save}\n"
puts sql
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment