Created
January 1, 2011 02:34
-
-
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)
This file contains 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
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