LoginSignup
2
0

More than 1 year has passed since last update.

【Rails】jbulderの基礎・使い方

Last updated at Posted at 2021-11-26

ポートフォリオ制作でjbuilderを使ったので学習した内容をまとめました。

jbuilderとは?

jbuilderとは、JSON形式のデータを簡単に作成することができるgem。Railにデフォルトで導入されている。

jbuilderでできること

app/view/〇〇.json.jbuilderファイル内のjsonオブジェクトに対して様々なメソッドを使うことでJSON形式の文字列のデータを簡単に作ることができる。

「APIを叩く」みたいなことができるのだと思います。(たぶん)
「APIを叩く」に関して、こちらの記事が大変参考になりました。

使い方

RailsとVue.jsを使用、取得するデータは作成済みの想定で進めます。

1. Jbuilderが導入されていることを確認する

Gemfile
ruby '2.7.3'
gem 'rails', '~> 6.1.4'
・・・
gem 'jbuilder', '~> 2.7'

2. コントローラーの準備

localhost/api/v1/comments.jsonでデータが扱えるようにするため、コントローラーの設定を行います。

app/controller/api/v1/comments_controller.rb
class Api::V1::CommentsController < ApiController
  def index
    @comments = Comment.all
  end
end

3. jbuilderファイルの作成

各メソッドは後術します。

app/views/api/v1/comments/index.json.jbuilder
json.set! :comments do
  json.array! @comments do |comment|
    json.extract! comment, :id, :context
  end
end

4. 生成されたjsonデータを確認

http://localhost/api/v1/comments.jsonにアクセス
※二点いかがわしいコメントがありましたので隠させていただきます。
スクリーンショット 2021-11-27 6.18.23.png

メソッド

  • json.extract!:第一引数に指定したインスタンス変数のデータをJSON形式の文字列で返す。
〇〇json.jbundler
json.extract! @commnet, :id, :context

# 実行結果=> {"id": 1, "context": "hogehoge"}
  • ネスト
    入れ子構造にして属性をまとめたい場合は以下のように記述。
〇〇json.jbundler
json.set! commnets do
  json.extract! @commnet, :id, :context
end
# 実行結果=> {"comments":[{"id": 1, "context": "hogehoge"}]}
  • json.set!:キーと値がペアとなったJSON形式の文字列を返す
〇〇json.jbundler
json.set! "context", "hogehoge"
# 実行結果=> {"context": "hogehoge"}
  • json.array!:モデル内のデータが配列に格納され、JSON形式の文字列のデータで返す
〇〇json.jbundler
json.array! @comments, :id, :context
# 実行結果=> [{"id": 1, "context": "hogehoge"},{"id": 2, "context": "hojihoji"}]

 参考記事

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