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
PostgreSQL offers two types for storing JSON data: json and jsonb . To implement efficient query mechanisms for these data types, PostgreSQL also provides the jsonpath data type described in Section 8.14. 7. The json and jsonb data types accept almost identical sets of values as input.
One simple difference between JSON and jsonb data type is that JSON stores the exact copy of the data represented/ inputted in the JSON format to the user whereas jsonb stores the data in the binary format which means that the input data is first processed and then stored in the binary form.
Because JSONB stores data in a binary format, queries process significantly faster. Storing data in binary form allows Postgres to access a particular JSON key-value pair without reading the entire JSON record.
JSON-B is a standard binding layer for converting Java objects to/from JSON messages. It defines a default mapping algorithm for converting existing Java classes to JSON, while enabling developers to customize the mapping process through the use of Java annotations.
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"}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With