todoアプリを作っていて、todoListモデルの全てをjsonに書き出す場合の手順
routeの設定
api/todo/へアクセスしたときに、indexアクションが実行されるようにroutes.rbを設定します。
config/routes.rb
namespace :api do
namespace :todo do
get '/', action: 'index'
end
end
コントローラーの記述
renderのところでjbuilderへ渡すように記述します。
app/controllers/api/todo_controller.rb
class Api::TodoController < ApplicationController
def index
@sample_todoes = Todo.all
render 'index', formats: 'json', handlers: 'jbuilder'
end
end
jbudilerの記述
viewとしてjbuilderを以下のように記述します。
なんかもっといい書き方があるんだろうか。
app/views/api/todo/index.json.jbuilder
json.todo do |json|
json.array!(@sample_todoes) do |todo|
json.extract! todo, ;id, :title, :done
end
end
ブラウザで確認
{
"todo":[
{"title":"test投稿todo","done":false},
{"title":"test投稿2","done":true}
]
}