TheRealJimShady
TheRealJimShady

Reputation: 4303

Rails Serialized JSON -> no implicit conversion of Hash into String

Having collected some JSON from a file using the Curb gem, I assign a portion of it to an instance variable:

self.json_stuff = {"title" => json["title"], "description" => json["description"], "image" => json["image"]}.to_json

This then gets stored in the database as JSON:

serialize :json_stuff, JSON
...
self.save

Later on I check for the presence of said json_stuff:

return self.json_stuff.present?

And get the following error:

TypeError - no implicit conversion of Hash into String:
  json (1.8.3) lib/json/common.rb:155:in `initialize'
  json (1.8.3) lib/json/common.rb:155:in `new'
  json (1.8.3) lib/json/common.rb:155:in `parse'

I've stepped through the code and I know that the collection of the JSON from the file is done without issue.

Upvotes: 1

Views: 2731

Answers (1)

Roope Hakulinen
Roope Hakulinen

Reputation: 7405

As far as I know, the present? method is for Strings to check if they are not empty. If you just want to return boolean based on the existence of json_stuff you should check if it is nil for example with

return self.json_stuff.nil?

The type of self.json_stuff is Hash instead of String.

Upvotes: 1

Related Questions