Using jbuilder

In the .json.jbuilder file, we use json object to defile the output JSON node. the syntax in json.any_name, Then passing the value as argument.

For example, jsor.id(@album.id) will output {id: 123}

So, for the album show API, we can create a file named show.json.jbuilder inside views/albums/ folder.

1json.id @album.id
2json.title @album.title

Or we can create a new node by using the json.name do |json| end block.

The following is an album information with the user basic information.

1json.id @album.id
2json.title @album.title
3json.created_at @album.created_at
4json.link album_url(@album)
5json.user do |json|
6  json.id @album.user.id
7  json.email @album.user.email
8end

How about listind all the photos in the album?

1# photos
2json.photos @album.photos do |json, photo|
3  json.id photo.id
4  json.title photo.title
5  json.image_url request.protocol + request.host_with_port + photo.file.url
6  json.thumb_url request.protocol + request.host_with_port + photo.file.url(:thumb)
7end

The image_url is a little but tricky, the paperclip gem returns relative url only.

we can prepend the URL to the relative path, and the URL is composited by the protocol and host_with_port

If you feel uncomfortable with the long string concatenation here, helper is the place to abstract that long line.

What’s next? We’re going to take a look at “Extracting view code to helpers”.

overlaied image when clicked on thumbnail

Makzan | Ruby on rails 101 | Table of Content