7

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
1
  • Let check any error in your console when doing this? 2 your commands should work fine! Commented Feb 12, 2016 at 10:45

2 Answers 2

8

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"}
Sign up to request clarification or add additional context in comments.

3 Comments

am Using Rails 5.1.4 and seems that saving a json string in a JSONB field will save it as string and not as a hash
from what I found this is the new behavior starting from v5.0.0 here is the source github.com/rails/rails/commit
@medBouzid I think that bug is already fixed in newest rails
1

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

1 Comment

Well, it's just that you must have a string column in the database, and that you must give the hash itself as an argument of update, not an already serialized verison of it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.