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, will output {id: 123}

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

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

The following is an album information with the user basic information.
2json.title @album.title
3json.created_at @album.created_at album_url(@album)
5json.user do |json|

How about listind all the photos in the album?

1# photos do |json, photo|
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)

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