ruby 在这种情况下,如何在Rails7控制器响应中传递额外的计算字段

i7uq4tfw  于 2023-08-04  发布在  Ruby
关注(0)|答案(2)|浏览(88)

我得到了以下代码:

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,这是我的模型中的一个方法。

jei2mxaa

jei2mxaa1#

如果是“标准”rails序列化,则可以覆盖Task模型中的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

kd3sttzy

kd3sttzy2#

最后是这样做的:

def index
    tasks = current_user.tasks.all.page(params[:page] || 1)
    arr = []
    tasks.each do |task|
      authorize!(:read, task)

      extra_fields = { 'folder_name' => task.folder.name,
                       'project_name' => task.folder.project.name,
                       'project_id' => task.folder.project_id,
                       'active_time_entries' => JSON.parse(task.time_entries.where(end_date: nil).all.to_json) }

      arr << JSON.parse(task.to_json).merge(extra_fields)
    end

    render(json: { success: true, data: arr, meta: pagination_info(tasks) }.to_json)
  end

字符串
希望它能在未来帮助到某人。

相关问题