【问题标题】:Rails 4: How to store array of custom-class objects as an attribute?Rails 4:如何将自定义类对象数组存储为属性?
【发布时间】:2014-08-13 09:23:27
【问题描述】:

我正在尝试使用 Store 将自定义集群类对象的数组存储为属性

现在的问题是,当向 JSON 编码器传递 array 对象时,例如:

 [
   4.25, 136.25: 4 points, quant: 285.06307738701975,
   47.5, 905.0: 2 points, quant: 11.180339887498949
 ]

这存储为:

[{"center"=>{"coords"=>{"x"=>5.5, "y"=>207.5}},
  "points"=>
   [{"coords"=>{"x"=>6.0, "y"=>195.0}, "z"=>8},
    {"coords"=>{"x"=>5.0, "y"=>220.0}, "z"=>9}],
  "moved"=>false},
 {"center"=>{"coords"=>{"x"=>3.0, "y"=>65.0}},
  "points"=>
   [{"coords"=>{"x"=>4.0, "y"=>70.0}, "z"=>12},
    {"coords"=>{"x"=>2.0, "y"=>60.0}, "z"=>13}],
  "moved"=>false},
 {"center"=>{"coords"=>{"x"=>47.5, "y"=>905.0}},
  "points"=>
   [{"coords"=>{"x"=>50.0, "y"=>900.0}, "z"=>10},
    {"coords"=>{"x"=>45.0, "y"=>910.0}, "z"=>11}],
  "moved"=>false}]

因此,对于每个数组元素,我得到的不是 Cluster 类,而是 ActiveSupport::HashWithIndifferentAccess。如果我不使用 json,它就会完全崩溃。 Ruby 无法将 4.25, 136.25: 4 points, quant: 285.06307738701975, 读取为来自属性 hash 的对象。

我还有其他选项可以将非标准对象作为数组存储在属性中吗?

【问题讨论】:

    标签: ruby-on-rails ruby arrays json store


    【解决方案1】:

    为此找到了另一个解决方案 - 我没有使用带有 json 的 ActiveRecord::Store,而是使用 serialize 方法制作了一些东西:

    serialize :cluster_array, Array
    

    所以现在我可以将集群对象数组保存为属性。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-28
      • 2023-03-12
      • 1970-01-01
      • 2018-06-04
      • 1970-01-01
      相关资源
      最近更新 更多