如何在Rails中使用嵌套数组的PostreSQL hstore?

B S*_*ven 5 arrays postgresql hash ruby-on-rails hstore

移民:

class Preference < ActiveRecord::Migration

  def change
    enable_extension 'hstore'

    create_table :preferences do |t|
      t.hstore :prefs
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

模型:

class Preference < ActiveRecord::Base
  store_accessor :prefs
end
Run Code Online (Sandbox Code Playgroud)

这似乎有效,如果prefs是一个哈希{ email:'yes' },但不适用于内部数组的哈希:{ email:[ 'monday', 'tuesday' ]}.

拉出哈希时,数组将保存为JSON.

是否有一种使用嵌套哈希和数组的hstore的好方法?

我确实尝试添加array:true迁移,但这似乎只允许保存数组而不是哈希.

如何使用嵌套哈希和数组的Rails PostgreSQL hstore?

Rails 4.2.4,PostgreSQL 9.3.5

Joe*_*oel 9

PostgreSQL hstore旨在存储文本字符串的键值对.看看hstore文档.

我使用JSON类型将数组存储为散列内的值.有两种JSON数据类型:JSON和JSONB.JSONB支持索引但速度稍慢,而JSON不支持索引但速度更快.你可以在这里阅读它们: JSON Type.

我会做以下事情:

class Preference < ActiveRecord::Migration
  def change
    create_table :preferences do |t|
      t.json :prefs
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

在array: truehstore列上的旁注设置意味着您要存储一组hstores.