JSON is a native data type in PostgreSQL since 9.2 and now also a first class citizen in Rails!
In this article we will learn how to persist and save object data more easily.
1. Create your Migration
I can confirm that PostgreSQL has native support, check your database documentation for other support questions!
2. Saving JSON data in your database
Top Secret Tip: Its EXACTLY the same as saving regular attributes!
REMEMBER that symbols in your hashes will be converted to strings!
JSON does not have knowledge of ruby symbols!
3. Can we Query JSON attributes!?!
Lets find all users that have confirmed the newsletter and their favorite cheese is
The final query will look like this:
Lets look at the first
::json will make sure your data is a JSON type.
->> is used for top level
Now lets query against the NESTED JSON data:
#>> is used to Get JSON objects at a specified path!
YOU DID IT!
Now you can query against your JSON Data is Rails with PostgreSQL!