mak*_*dad 6 postgresql json ruby-on-rails ruby-on-rails-3
我刚刚将Postgres json类型添加到正在使用的Rails / Active Record表中。我想用Rails装置中的默认值填充记录:
fixture_id:
existing_column: "foobar"
newly_added_column: <%= JSON.dump({:reason => 'foobar'}) %>
Run Code Online (Sandbox Code Playgroud)
以前,我以这种方式将字符串化的JSON存储在text列中。但是,当我现在运行此单元测试时:
test "my test" do
sut = fixtures(:fixture_id)
assert_not_nil sut.newly_added_column
end
Run Code Online (Sandbox Code Playgroud)
测试失败。因为它在数据库级别是JSON,所以我认为将其转储为字符串不是有用的,但是YAML固定装置似乎无法将对象保留为Hash(当我尝试不使用时JSON.dump,会得到ActiveRecord::Fixture::FormatError: a YAML error occurred parsing)。
请注意,我使用的是Rails 3,因此我认为对此有一些支持,但在Rails 3中,添加jsonPostgres列类型的迁移仍然有效。
小智 8
为了避免在你的装置中内联冗长的 JSON 结构,YAML 提供了一个有用的>操作符
fixture_id:
existing_column: "foobar"
data: >
{
"can_edit": true,
"can_se": true,
"can_share": true,
"something_else": true
}
Run Code Online (Sandbox Code Playgroud)
在 Rails 5 中,可以用 YAML 格式简单地描述 JSON。当灯具加载到数据库中时,它将被转换为正确的 JSON:
parent:
name: A fixture
json_field:
- name: JSON Object 1
foo: bar
- name: JSON Object 2
foo: baz
Run Code Online (Sandbox Code Playgroud)
(在 Postgres 中使用 JSONB 属性进行测试)
小智 6
我相信您的装置可以很简单:
fixture_id:
existing_column: foobar
newly_added_column: {'reason':'foobar'}
Run Code Online (Sandbox Code Playgroud)