LoginSignup
3
1

More than 5 years have passed since last update.

【Rails】JSONの形式で必要な値だけを返す方法

Last updated at Posted at 2018-10-22

JSONとは

データをやりとりする際の形式のことです。
2018年現在、「謎の拡張子JSON」とニュースの記事になる程度には広く使われています。

JSON形式のデータを返す

controllerのアクションの処理で該当するviewのディレクトリに
新規ファイルをファイル名.json.jbuilderとなるように作成します。
今までhtml.rbが格納されていた場所ですね。

テンプレートの形式

curlコマンドで、きちんと動くか該当のアクションを叩いてみた所、下の内容が返ってきました。

$ curl http://localhost:3000/api/users/1
{"user":{
"id":1,
"email":"hoge@gmail.com",
"crypted_password":"〜〜〜〜",
"salt":"〜〜〜〜",
"created_at":"2018-10-15T03:57:04.000Z",
"updated_at":"2018-10-15T03:57:04.000Z",
"reset_password_token":null,
"reset_password_token_expires_at":null,
"reset_password_email_sent_at":null,
"access_count_to_reset_password_page":0,
"name":""}

jbuilderファイルに何も記述をしないと作成日時や更新日時も合わせて送られる仕様のようです。

特定の値だけを返すようにする

先ほど作成したjbuilderファイルに、記述を足して欲しいデータだけを返すように渡す内容を絞ります。
今回は、下記の3つだけが返るように絞ってみました。

1.id
2.メールアドレス
3.名前

view/app/users/ahow.json.jbuilder
json.extract! user, :id, :email, :name

検証

$ curl http://localhost:3000/api/users/1
{"id":1,"email":"hoge@gmail.com","name":""}

jbuilderファイルにて返す項目を絞ったところ、きちんと必要なデータだけが返ってきました。

今日はこのあたりで失礼します。

3
1
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
1