Search code examples
sqlruby-on-railsrubypostgresqlhstore

How to rename hstore key in Rails + Postgres


How to rename hstore key in Rails 4 with Postgres?

User.update_all('hstorename -> oldcolumname: newcolumnname') ???

Solution

  • Based on https://stackoverflow.com/a/13276545/305019

      def change_hstore_key(klass, h, from_key, to_key)
        klass.where("#{h} ? '#{from_key}'")
             .update_all("#{h} = (#{h} - '#{from_key}'::text) || " \
                         "hstore('#{to_key}'::text, #{h} -> '#{from_key}')")
      end
    
      # usage
      change_hstore_key(User, hstorename, oldcolumnname, newcolumnname)
    

    IMPORTANT: Do not use this with any user-supplied params to avoid SQL injection. For migrations etc where you provide all data, this should do the trick.