Last active
August 29, 2015 13:56
-
-
Save ryz310/9226581 to your computer and use it in GitHub Desktop.
FactoryGirl 等で作成したデータを Insert文に変換する
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
def create_insert_into(model_class) | |
model_class.all.each do |record| | |
print "insert into #{model_class.table_name} values (" | |
model_class.columns.each_with_index do |col, idx| | |
print ", " unless idx == 0 | |
print "#{sql record.public_send(col.name)}" | |
end | |
puts ");" | |
end | |
end | |
def sql(data) | |
case data | |
when DateTime, Time | |
"'#{data.to_s(:db)}'" | |
when TrueClass | |
"'1'" | |
when FalseClass | |
"'0'" | |
when NilClass | |
"NULL" | |
else | |
"'#{data}'" | |
end | |
end | |
# Usage | |
FactoryGirl.create(:table_name) | |
create_insert_into(TableName) # => insert into values('data1', 'data2', ...); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment