Ruby on rails 如何在Rails中使用带有嵌套数组的PostreSQL hstore?

Ruby on rails 如何在Rails中使用带有嵌套数组的PostreSQL hstore?,ruby-on-rails,arrays,postgresql,hash,hstore,Ruby On Rails,Arrays,Postgresql,Hash,Hstore,迁移: class Preference < ActiveRecord::Migration def change enable_extension 'hstore' create_table :preferences do |t| t.hstore :prefs end end end 类首选项

迁移:

class Preference < ActiveRecord::Migration

  def change
    enable_extension 'hstore'

    create_table :preferences do |t|
      t.hstore :prefs
    end
  end
end
类首选项
型号:

class Preference < ActiveRecord::Base
  store_accessor :prefs
end
类首选项
如果prefs是一个散列,如
{email:'yes'}
,但对于内部有数组的散列,
{email:['monday',周二']}
,这似乎是可行的

拉出散列时,数组保存为JSON

有没有一种好方法可以将hstore与嵌套哈希和数组一起使用

我确实尝试将
array:true
添加到迁移中,但这似乎只允许保存数组而不是散列

如何将Rails PostgreSQL hstore与嵌套哈希和数组一起使用


Rails 4.2.4、PostgreSQL 9.3.5

您只需在access上解析JSON即可:

class Preference < ActiveRecord::Base
  def prefs
    self[:pref] = json_parse_values self[:pref]
  end

  private
  def json_parse_values(hash)
    hash.map do |key, val|
      begin
        [key, (val.is_a?(String) ? JSON.parse(val) : val)]
      rescue JSON::ParserError => e  
        [key, val]
      end 
    end.to_h
  end
end
类首选项e
[键,val]
结束
完
结束
结束

解析方法仅当值是字符串时才尝试解析该值。如果它引发一个
parserror
,我们只使用字符串。

PostgreSQL hstore用于存储文本字符串的键值对。请看下面的图片

我使用JSON类型将数组作为值存储在散列中。有两种JSON数据类型:JSON和JSONB。JSONB支持索引,但速度稍慢,而JSON不支持索引,但速度更快。您可以在此处阅读有关它们的信息:

我会这样做:

class Preference < ActiveRecord::Migration
  def change
    create_table :preferences do |t|
      t.json :prefs
    end
  end
end
类首选项

另一方面,在hstore列上设置
array:true
意味着您希望存储一个hstore数组。

这就是我现在使用的解决方案。工作正常,只是它似乎不支持索引。是的,你是对的。有两种JSON数据类型:JSON和jsonb。jsonb支持索引,而且您需要PostgreSQL 9.4来支持
jsonb
,不?@muistooshort似乎就是这样。我链接到的文档是针对9.4的