Quick note for creating API using jbuilder

Katz F
1 min readApr 5, 2016

--

1. Create a model
If you are starting from scratch,

rails g scaffold Titles param1:string param2:boolean

or if you wanna add some columns to DB table, then do

rails generate migration AddDetailsToTitles price:integer author:string

Don’t forget to do rake db:migrate

2. Edit a controller to render json

respond_to do |format|
format.html # app/views/titles/index.html.erb
format.json # app/views/titles/index.json.jbuilder
end

3. Edit a jbuilder file

The basic use of jbuilder is as follows

json.user do |json|
json.nickname @user.name
end
# the above code will return{
“user”: {
“nickname”: “sasata299”
}
}

If you wanna use a template


json.partial! ‘api/v1/titles/template’, title: title

and create a file and name it api/v1/titles/_template.json.jbuilder

json.ignore_nil!
json.id title.id
json.title title.name

--

--

Katz F

www.katsuyaf.com — CTO at Runopia and Ph.D Candidate at the University of Tokyo. Former HCI researcher at MIT Media Lab.