LoginSignup
1
0

More than 3 years have passed since last update.

RoRでJSONを出力する際にテーブルの列名とキー値が異なる時の対処

Posted at

やりたいこと

fullcalendarで以下の様に予定を表示させたい。
スクリーンショット 2019-09-01 9.37.20.png

表示させるために

以下の様なJSONを出力する必要があります。
json
{"title":"テスト","start":"2019-09-01T09:00:00.000Z","end":"2019-08-29T10:00:00.000Z"}

テーブルの列名はname,from_time,to_timeとなっていて、
それぞれ
title ⇔ activity_name
start ⇔ from_time
end ⇔ to_time
として紐づいています。

自分の環境

  • Linux Debian 10.0(Docker上)
  • ruby 2.6.3p62
  • Rails 5.2.3

current_userはログインしているuserを返す自作ヘルパーです。
userとactivity_historysは1:Nの関係です。

実装したコード(最終形)

controller.rb
    act_histories = current_user.activity_historys.select(
      "activity_name AS title,
      from_time AS start,
      to_time   AS end"
    ).as_json(only: [:title, :start, :end])

      respond_to do |format|
      format.json {
        render json: act_histories.to_json
      }

没になったコードその1

controller.rb
   act_histories = current_user.activity_historys

    array = []

    actHistorys.each do |act|
      hash = {}
      hash.store(
        "title", act.activity_name
      )
      hash.store(
        "start", act.from_time
      )
      hash.store(
        "end", act.to_time
      )
      array.push(hash)
    end

    respond_to do |format|
      format.json {
        render json: act_histories.to_json
      }
    end

単純にコード量が多い。また、データ量が多いと処理速度が下がるのではと思い、SQLのAS句を使用したくななりました。

没になったコードその2

controller.rb
    act_histories = current_user.activity_historys.select(
      "activity_name AS title,
      from_time AS start,
      to_time   AS end"
    )

    respond_to do |format|
      format.json {
        render json: act_histories.to_json
      }
{"id":null,"title":"テスト","start":"2019-09-01T09:00:00.000Z","end":"2019-08-29T10:00:00.000Z"}

idカラム指定していないのにidがNULLとして出力される...
idいらないんじゃ!

没になったコードその3

controller.rb
    act_histories = current_user.activity_historys.select(
      "activity_name AS title,
      from_time AS start,
      to_time   AS end"
    ).pluck(:activity_name, :from_time, :to_time)

    respond_to do |format|
      format.json {
        render json: act_histories.to_json
      }
["テスト","2019-09-01T09:00:00.000Z","2019-08-29T10:00:00.000Z"]

as句で指定した列別名が消えてしまう。

まとめ

  • テーブルの列名とキー値が異なる時はselectメソッドで列別名をつける
  • idがNULLになるのはas_jsonでonオプションを指定する

参考にさせていただいたページ

https://qiita.com/TakakiSato/items/f4192611a4737323fcb4
https://qiita.com/k-o-u/items/31e4a2f9f5d2a3c7867f
https://railsguides.jp/active_record_querying.html
https://fullcalendar.io/docs/v3/events-json-feed

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