我将 Ruby On Rails 与 PostgreSQL 数据库一起使用。出于性能原因,我使用带有哈希数组的 jsonb-field ,而不是将其提取到特定的表中。在现实世界中,这个斑点看起来像
[ { "row": 1, "price": 0, "column": 1, "status": 1, "index_row": 1, "contingency": 0, "index_column": 1 }, { "row": 1, "price": 0, "column": 2, "status": 1, "index_row": 1, "contingency": 0, "index_column": 2 }... ]
并且工作正常。
现在我尝试增加测试覆盖率并注意到,我无法使用标准夹具方法创建哈希数组。假设如下:
CREATE TABLE IF NOT EXISTS public.circles
(
id bigint NOT NULL DEFAULT nextval('circles_id_seq'::regclass),
blob jsonb
)
和一个包含以下内容的固定文件circles.yml:
templatecircle_1:
blob: <%= [1, 2] %>
运行 bin/rails 测试时,这可以按预期工作。
templatecircle_1:
blob: {"abc": "def"}
这也符合预期。
但是,
templatecircle_1:
blob: <%= [1, {"abc": "def"}] %>
产生 ActiveRecord::Fixture::FormatError:
请注意,YAML 必须使用空格一致缩进。不允许使用制表符。错误:():在第 2 行第 11 列解析流节点时未找到预期的节点内容
我什至尝试使用以下解决方法:
templatecircle_1:
blob: <%= JSON.parse("[1, {\"abc\": \"def\"}]") %>
这给出了同样的错误。
有人知道如何在 RoR 装置中创建哈希数组吗?
要定义“哈希数组”字段,只需对每个数组元素使用
-
表示法,对每个哈希键/值对使用 :
:
templatecircle_1:
blob:
- row: 1
price: 0
column: 1
status: 1
index_row: 1
contingency: 0
index_column: 1
- row: 1
price: 0
column: 2
status: 1
index_row: 1
contingency: 0
index_column: 2
之后您可以调用您的测试
Circle.first.blob
# => [{"row"=>1, "price"=>0, "column"=>1, "status"=>1, "index_row"=>1, "contingency"=>0, "index_column"=>1}, {"row"=>1, "price"=>0, "column"=>2, "status"=>1, "index_row"=>1, "contingency"=>0, "index_column"=>2}]