Skip to content

Instantly share code, notes, and snippets.

@afgomez
Created February 27, 2012 12:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save afgomez/1923380 to your computer and use it in GitHub Desktop.
Save afgomez/1923380 to your computer and use it in GitHub Desktop.
Convert a hash into a valid key=value SQL string
# gives a valid key=value SQL string for using in "INSERT INTO `table` SET" sentences
# >> "INSERT INTO `table_name` SET #{sqlize(Model.find(id).attributes)};"
# returns
# => "INSERT INTO `table_name` SET `attr1`=value1,`attr2`=value2..."
# Handles different datatypes
def sqlize hash
hash.map do |k,v|
v = case v
when Time
%{"#{v.to_s(:db)}"}
when TrueClass
1
when FalseClass
0
when NilClass
"NULL"
when String
%{"#{v.gsub(/['"\\\x0]/,'\\\\\0')}"}
else
v
end
"`#{k}`=#{v}"
end.join(',')
end
@littlemove
Copy link

ActiveRecord::Base implementa esto en sanitize_sql_hash_for_assignment:

ActiveRecord::Base.send(:sanitize_sql_hash_for_assignment,{:wadus=> 'wadus', :foo => nil})

=> "foo = NULL, wadus = 'wadus'"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment