Skip to content

22b API Jbuilder Views

Dave Strus edited this page Jul 18, 2015 · 1 revision

Solution

app/controllers/api/v1/notes_controller.rb

class API::V1::NotesController < ApplicationController

  def index
    @notes = Note.all
    respond_to :json
  end

  def show
    @note = Note.find params[:id]
    respond_to :json
  end

end

app/views/api/v1/notes/show.json.jbuilder

json.extract! @note, :id, :title, :body_text, :body_html, :created_at, :updated_at
json.user @note.username

OR

app/views/api/v1/notes/show.json.jbuilder

json.note do
  json.id         @note.id
  json.title      @note.title
  json.body_html  @note.body_html
  json.created_at @note.created_at
  json.updated_at @note.updated_at
  json.user       @note.user.username
end

Default format

We can save ourselves from typing respond_to :json in every single action (since this is a JSON API...) by setting the default to 'json' like this:

namespace :api, defaults: { format: 'json' } do
  namespace :v1 do
    resources :notes
  end
end

The default format also allows us to get a response from /api/v1/notes in addition to /api/v1/notes.json.

And now we can remove all respond_to :json calls in the API controllers.

If we load localhost:3000/api/v1/notes.json in a browser now, we should see our note data as well as a URL that we can click (or consume) to get to the data for each note.

Now is a good time to commit if everything is working as expected.