Techioz Blog

このコンテキストで、Rails 7 コントローラーの応答で追加の計算フィールドを渡すにはどうすればよいですか?

概要

次のコードがあります:

class TasksController < ApplicationController
  before_action :authenticate_user!

  def index
    tasks = current_user.tasks.all.page(params[:page] || 1)

    tasks.each do |task|
      authorize!(:read, task)

      task.merge(total_duration_of_time_entries => task.total_duration_of_time_entries)
    end

    render_data(tasks)
  end

タスク配列に追加のフィールドを追加するにはどうすればよいですか?私のモデルのメソッドである total_duration_of_time_entries を追加しようとしています。

解決策

「標準」の Rails シリアル化の場合は、タスク モデルの as_json メソッドをオーバーライドできます。

def as_json(options = nil)
  super.merge(total_duration_of_time_entries:) # also use value if it is old Ruby
end

ただし、シリアライザー (例: blueprinter) または JSON テンプレート ジェネレーター (例: jbuilder) を使用する方がより柔軟です。