-
Notifications
You must be signed in to change notification settings - Fork 0
22b API Jbuilder Views
Dave Strus edited this page Nov 18, 2014
·
1 revision
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
endapp/views/api/v1/notes/show.json.jbuilder
json.extract! @note, :id, :title, :body_text, :body_html, :created_at, :updated_at
json.user @note.user.nameWe 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
endThe 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.