Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I put a Postgres JSON value into a Rails fixture?

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.

like image 772
makdad Avatar asked May 03 '16 13:05

makdad


People also ask

How do I query JSON data in PostgreSQL?

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.

Is PostgreSQL good for JSON?

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.

What is PostgreSQL JSON?

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.


2 Answers

I believe your fixture can be as simple as:

fixture_id:
  existing_column: foobar
  newly_added_column: {'reason':'foobar'}
like image 148
bmsatierf Avatar answered Oct 19 '22 19:10

bmsatierf


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
    }
like image 11
twenizaak Avatar answered Oct 19 '22 18:10

twenizaak