In the past, it could be really cumbersome to build proper JSON data feeds. Fortunately Ruby on Rails makes dealing with JSON much easier. Today we will learn how to use the JBuilder gem, which will allow us to easily build complex data feeds.
First, we need to include the gem in our gemfile. Recent versions of Ruby on Rails include this gem commented out towards the bottom of the file. In addition, Rails 4 already includes this gem so you don’t need to do anything. If it is in your gemfile and it is commented out, uncomment it, otherwise, add the gem using the line shown below.
1
|
|
Then run a bundle install:
1
|
|
Next, we will need a model and some sample data. In this sample project we will have 2 models. A product model, and a review model, which will be associated with products. Lets generate these 2 models now. Run the commands below to create the models and migrate the database:
1 2 3 |
|
Excellent, Now lets add some seed data. Copy and paste the following seed data into your seeds.rb file:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
|
Next, run the seed command to populate your database:
1
|
|
Well, we now have a database populated with products and reviews. Next we will need to set up the association between our products and our reviews. First, open up the Product model and modify it so that it looks like the code listed below:
1 2 3 |
|
Great, now lets add the reverse association. Open up your Review model and verify that it looks like the code listed below. Rails should auto populate this, but double check just to be sure.
1 2 3 |
|
With the database model created, our data populated, and our associations set up, now it’s time to create a controller. Run the command below to create products controller.
1
|
|
Now, lets make a change to our routes.rb file so that our controller becomes a resourceful controller. Replace the line that says get “products/index” with the code listed below.
1 2 |
|
This sets up the products controller as a resourceful controller. Now, in order to create a json feed using jbuilder, we must create a jbuilder view. Create a new file in app/views/products called index.json.jbuilder and add the code listed below.
1 2 |
|
Excellent. Now if you navigate to http://localhost:3000/products.json You will see an empty json data feed. Now, lets add some content to that data feed. Now, open up the products controller and modify it so that it looks like the code listed below.
1 2 3 4 5 |
|
Next, Open the jbuilder file again and modify it so that it looks like the code listed below.
1 2 3 4 5 |
|
Excellent, now if we refresh the page we will see a listing of products in json format. Now lets add the reviews. Modify your code so that it looks like the code listed below.
1 2 3 4 5 6 7 8 9 10 11 |
|
Excellent! Now if we refresh the page we’ll see the review listing for each product. That’s it folks! That’s all there is to using the jbuilder gem.
So far so good, That’s it!!! See ya!!! :)