【问题标题】:Array of Hashes with ActiveRecord带有 ActiveRecord 的哈希数组
【发布时间】:2014-03-23 20:45:05
【问题描述】:

ActiveRecord (Rails 4.0) 支持 PostgreSQL Hstore 和 Array 数据类型,因此理论上可以使用 Array of Hashes,但我的实现抛出:

PG::InvalidTextRepresentation: ERROR:  malformed array literal:

错误很明显(双引号冲突):

"{"null"=>"false","name"=>"schema_id","type"=>"integer","null"=>"false","name"=>"title","type"=>"text"}"

: INSERT INTO "entities" ("attribute_hash", "schema_id", "title") VALUES ($1, $2, $3) RETURNING "id"

解决方案对我来说并不明显,我该如何实施?

我的架构:

create_table :schemas do |t|
  t.text    :title
  t.timestamps
end

create_table :entities do |t|
  t.integer :schema_id,       null: false
  t.text    :title,           null: false
  t.hstore  :attribute_hash, array: true
end

我的种子:

@schema_id = Schema.create!(title: 'accreu')
Entity.create!(
  schema_id: @schema_id.id, title: 'entities',
  attribute_hash: [
    {null: "false", name: :schema_id, type: :integer},
    {null: "false", name: :title, type: :text}
   ]
)

【问题讨论】:

  • 您正在尝试使用 hstore 数组定义动态表架构?
  • @CraigRinger 对于我的应用程序,这是目前理想的模式。欢迎您分享您的替代方案,但我的问题是有效的,我正在寻找建设性的答复。
  • @muistooshort。目标是一个 hstore 数组,正确。
  • 我个人强烈怀疑具有外键关系的侧表比使用数组更可取,因此每个子记录都有一个 hstore 字段加上父 ID 和任何有用的固定字段.这样,您将使用经过测试和支持的功能。否则,如果您进行一些 ActiveRecord 错误修复,我不会感到太惊讶 - hstore 的数组很奇怪,目前可能无法对其进行测试和支持。
  • 我怀疑json 列会不会那么痛苦。

标签: ruby-on-rails postgresql activerecord


【解决方案1】:

这是 Rails 中已确认的错误,已在提交 7c32db1 中修复,该错误存在于 4.1.0.rc1 及更高版本中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-19
    • 1970-01-01
    • 2022-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-20
    相关资源
    最近更新 更多