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.
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. do |json|
 3  json.title @album.title
 4  json.created_at @album.created_at
 5 album_url(@album)
 7  # user
 8  json.user do |json|
11  end
13  # photos
14 do |json, photo|
15    json.partial! photo
16  end

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