LoginSignup
0
0

More than 1 year has passed since last update.

RailsのjbuilderでJSONを返してみる

Last updated at Posted at 2021-05-18

なぜやるのか

Railsで作成しているポモドーロToDoアプリのToDoタスクをAjaxで実装したい。
JSとRailsをつなげる..??には、RailsのタスクをJSON形式で出力する必要があるらしい。(ちょっとまだここよくわかってない)
jbuilder を使うことで、簡単にJSON形式のデータを出力することができる。

手順

まずはrailsアプリの新規作成

rails new myapp

移動してデータベース作成

cd myapp && rails db:create

タスクモデルを作成

rails g model Task name:string is_done:boolean

マイグレート

rails db:migrate

コンソールでデータを入れとく

 rails c

> Task.new(name: "タスクのテストです。JSONで飛ばせるかな")
> task1.save
> exit #で抜ける

コントローラーの作成

rails g controller tasks index

vimでルーティングを以下のように編集し、コントローラとビューを繋ぐ

config/routes.rb
  1 Rails.application.routes.draw do
  2   root 'tasks#index'

  3   # For details on the DSL available within this file, see https://guides.ru    byonrails.org/routing.html
  4 end

index.html.erbが既にありますが、以下コマンドでjson.jbuilderを作成&開きます

app/views/tasks/index.json.jbuilder
  1 json.array! @tasks, :name, :id, :created_at
app/controller/tasks_controller.rb
  1 class TasksController < ApplicationController
  2   def index
  3     @tasks = Task.all
  4     render :index, formats: :json, handlers: 'jbuilder'
  5   end
  6 end

rails s -p 3333でlocalhost:3000に繋ぐと...

表示させられました!

スクリーンショット 2021-05-18 13.05.07.png

curlコマンドでも見れるみたい。

curl localhost:3333
[{"name":"タスクのテストです。JSONで飛ばせるかな","id":1,"created_at":"2021-05-18T03:20:27.370Z"}]%

参考記事

今回の記事はほぼ以下の手順を踏襲しています。が、一部db:migrateが抜けていたり、Rails6に対応していない書き方だったりしたので、修正してQiitaにまとめてみました。

jbuilderの記述方法についてわかりやすい記事↓
【Rails】Jbuilderのメソッドについて調べてみた

0
0
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
0
0