LoginSignup
0
0

More than 5 years have passed since last update.

[rails] モデルに存在しない値をjsonフォーマットで返却する方法

Posted at

概要

モデルに存在しない値をjsonフォーマットで返却したい場合どうするのか。
答えは、アクション関数のrender jsonする際にto_jsonを使いmethodsのオプションにモデルの任意の関数を指定してあげればいいです。

言葉では伝えづらいので、、実際にやってみた結果を御覧ください。

改修前

Reportのスキーマがどうなっているかは説明を省きますが、
コントローラーで以下のようなアクションの実装をしていて、reports.jsonにGETリクエストするとモデルの内容をjsonで出力してくれます。

reports_controller.rb
  # GET /reports
  # GET /reports.json
  def index
    @reports = Report.all

    respond_to do |format|
      format.html { render :index }
      format.json { render json: @reports, status: :ok }
    end
  end
reports.json
[
  {
    "id": 4,
    "text": "hoge",
    "created_at": "2019-02-13T11:16:23.000+09:00",
    "updated_at": "2019-02-13T11:16:23.000+09:00",
    "deleted_at": null
  }
]

改修後

では、実際にどう実装するかをやってみます。
まずは、モデル側に任意の関数を実装してください。以下の関数ではcreated_atの値を日本人がわかりやすい日時の文字列フォーマットに変換しています。

report.rb
class Report < ApplicationRecord
  # 省略

  def created_at_formatted
    self.created_at.strftime("%Y年%-m月%-d日")
  end
end

次に、アクションの実装のrender jsonしてあげている箇所を以下のように変更してあげます。

reports_controller.rb
  # GET /reports
  # GET /reports.json
  def index
    @reports = Report.all

    respond_to do |format|
      format.html { render :index }
      format.json { render json: @reports.to_json(methods: :created_at_formatted), status: :ok }
    end
  end
-      format.json { render json: @reports, status: :ok }
+      format.json { render json: @reports.to_json(methods: :created_at_formatted), status: :ok }

そうしますと以下のようにモデルには存在しない値をjsonで返却することができました。

reports.json
[
  {
    "id": 4,
    "text": "hoge",
    "created_at": "2019-02-13T11:16:23.000+09:00",
    "updated_at": "2019-02-13T11:16:23.000+09:00",
    "deleted_at": null,
    "created_at_formatted": "2019年2月13日"
  }
]

以上になります。

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