LoginSignup
3
3

More than 5 years have passed since last update.

railsのjbuilderでモデルのデータを全て書き出す

Last updated at Posted at 2017-05-10

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}
  ]
}
3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3