如何在Rails+Postgres中重命名hstore密钥



如何用Postgres重命名Rails4中的hstore密钥?

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

基于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)

重要:不要将其与任何用户提供的参数一起使用,以避免SQL注入。对于您提供所有数据的迁移等,这应该可以做到。

最新更新