Partial json views

How about we need the photos JSON output in several API?

We can use partial too in the JSON JBuilder. Same as ERB partial that begins with an underscore _partial.html.erb.

Here is our _photo.json.jbuilder file. Please note that it only describe one photo object because the parent file handles the loop.

1json.id photo.id
2json.title photo.title
3json.image_url absolute_photo_url(photo)
4json.thumb_url absolute_photo_url(photo, :thumb)

And here is the full show.json.jbuilder file after using the partial.

 1json.data do |json|
 2  json.id @album.id
 3  json.title @album.title
 4  json.created_at @album.created_at
 5  json.link album_url(@album)
 6
 7  # user
 8  json.user do |json|
 9    json.id @album.user.id
10    json.email @album.user.email
11  end
12
13  # photos
14  json.photos @album.photos do |json, photo|
15    json.partial! photo
16  end
17end

Note: Since json.any_name will create any_name node, all json special method – such as json.partial! – uses the ! mark. Normally the ! mark is used to indicate dangerous method that changes itself.

What’s next? We’re going to take a look at “Introducing behavior driven development”.

overlaied image when clicked on thumbnail

Makzan | Ruby on rails 101 | Table of Content