mardi 3 mai 2016

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.

Aucun commentaire:

Enregistrer un commentaire