1

somoone 是否知道是否可以在 rails 4 中有 hstore 数组?我试过了

add_column :orders, :frozen_content, :hstore , array: true

但我得到了

 PG::Error: ERROR:  malformed array literal: 

当我尝试保存时

4

3 回答 3

3

In principle, yes, but as you've found it isn't being escaped correctly when saved. I've just today logged an issue about that, see https://github.com/rails/rails/issues/11135 (includes a fix patch and some demo code)

于 2013-06-27T14:31:59.273 回答
2

这是一个至少存在于 Rails 4.0.1 中的错误。

提出了一个拉取请求来修复它,但在它被合并之前,你可以对 Rails 进行猴子补丁:

# config/initializers/extensions/postgres.rb
module ActiveRecord
  module ConnectionAdapters
    class PostgreSQLColumn < Column
      module Cast
        private

          def quote_and_escape(value)
            case value
            when "NULL"
              value
            else
              "\"#{value.gsub(/(["\\])/, '\\\\\1')}\""
            end
          end
      end
    end
  end
end

旁注,我在 Rails 控制台中测试它时遇到了麻烦,因为那里没有加载初始化程序。你可以这样做:

load "#{Rails.root}/config/initializers/extensions/postgres.rb"
于 2013-11-30T14:19:19.287 回答
0

您可以起诉 activerecord-postgres-hstore gem:

https://github.com/engageis/activerecord-postgres-hstore

从文档:

  1. 创建一个 hstore 支持的字段:

    class Person < ActiveRecord::Base 序列化 :data, ActiveRecord::Coders::Hstore end

  2. 向其中添加字段:

    person = Person.new person.data['foo'] = 'bar' person.save

  3. 查询它:

    Perosn.where("数据 -> 'foo' = 'bar'")

Railscast #345(在付费墙后面)使用 activerecord-postgres-hstore gem 更详细地介绍了使用 hstore:

http://railscasts.com/episodes/345-hstore

注意:我还没有尝试使用 rails 4... YMMV。

于 2013-04-17T20:11:09.283 回答