Martin Verdejo
Martin Verdejo

Reputation: 1369

How to save a hash or json string into a jsonb field

I have a json string from my active admin from "{\"en\":\"Lorem\"}"

I want to save this in my question.name field, which is of postgres jsonb type.

class Question < ActiveRecord::Base
  serialize :name
end

# db/schema.rb
create_table "preset_questions", force: :cascade do |t|
  t.jsonb    "name",               default: {}
end

I've tried the following:

question.update(name:"{\"en\":\"Lorem\"}")
question.update(name:JSON.parse("{\"en\":\"Lorem\"}"))

Result for both:

question.name
=> nil

Upvotes: 7

Views: 11365

Answers (2)

Martin Verdejo
Martin Verdejo

Reputation: 1369

Got it to work by removing serialize :name. Looks like rails already knows what to do given that the column type is jsonb

class Question < ActiveRecord::Base
end

# db/schema.rb
create_table "preset_questions", force: :cascade do |t|
  t.jsonb    "name",               default: {} 
end

question.update(name:"{\"en\":\"Lorem\"}")
question.update(name:JSON.parse("{\"en\":\"Lorem\"}"))

Both return

question.name
=> {"en"=>"lorem", "id"=>"ipsum"}

Upvotes: 8

Caillou
Caillou

Reputation: 1500

In Rails, you can specify in your ActiveRecord Model that it must serialize a column before saving it, and unserialize it after reading it. It makes you able to save any structure in a string column of your database.

class Question < ActiveRecord::Base
   serialize :name
end

Then you can save your hash just like this :

question.update(name: {en: "Lorem"} }

Documentation : http://api.rubyonrails.org/classes/ActiveRecord/AttributeMethods/Serialization/ClassMethods.html

Upvotes: 1

Related Questions