I just added a Postgres json
type to a Rails/Active Record table I'm working with.
I'd like to populate a record with a default value in Rails fixtures:
fixture_id:
existing_column: "foobar"
newly_added_column: <%= JSON.dump({:reason => 'foobar'}) %>
Previously, I'd stored stringified JSON this way in a text
column. However, when I now run this unit test:
test "my test" do
sut = fixtures(:fixture_id)
assert_not_nil sut.newly_added_column
end
The test fails. Because it is JSON at the database level, I don't think it's useful to dump it to a string, but the YAML fixtures can't seem to keep an object as a Hash (when I try it without the JSON.dump
, I get ActiveRecord::Fixture::FormatError: a YAML error occurred parsing
).
Mind you, I am using Rails 3, so I think some of the support for this may be in Rails 4, but in Rails 3, the migration to add a json
Postgres column type still work.
Querying the JSON documentPostgreSQL has two native operators -> and ->> to query JSON documents. The first operator -> returns a JSON object, while the operator ->> returns text. These operators work on both JSON as well as JSONB columns. There are additional operators available for JSONB columns.
If you're using static JSON data and active data that's structured for SQL storage, Postgres is a good shout — its JSONB representation is efficient and allows for indexing.
JSON is an open standard format that consists of key-value pairs. The main usage of JSON is to transport data between a server and a web application. Unlike other formats, JSON is human-readable text. PostgreSQL supports native JSON data type since version 9.2.
I believe your fixture can be as simple as:
fixture_id:
existing_column: foobar
newly_added_column: {'reason':'foobar'}
To avoid having lengthy JSON structure inline in your fixtures, YAML provide a useful >
operator
fixture_id:
existing_column: "foobar"
data: >
{
"can_edit": true,
"can_se": true,
"can_share": true,
"something_else": true
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With