【问题标题】:Rails to Render JSON with Newly Calculated Value for Each Element of a Rendered CollectionRails 为渲染集合的每个元素使用新计算的值渲染 JSON
【发布时间】:2021-04-03 10:45:19
【问题描述】:

我想向集合的每个元素添加一个新计算的值,当查询 Rails API 路由时,该集合呈现为render json:

这是当前的设置:

# app/Models

class User < ApplicationRecord
    has_many :pools, through: :user_pool
end

class Pool < ApplicationRecord
    has_many :users, through: :user_pool
    has_many :stakes

    def average()
        some_kind_of_average(self.stakes)
    end
end
# app/controllers/pool_controller.rb

  def index
    @user = current_user
    @pools = @user.pools
    render json: @pools, only: [:ticker, :id]
  end

我想做的是为@pools 集合中的每个pool 添加一个pool.average 的值。

应该是这样的:

# app/controllers/pool_controller.rb

  def index
    @user = current_user
    @pools = @user.pools
    render json: @pools, only: [:ticker, :id, average: @pools.each {|pool| pool.average}]
  end

以上当然行不通,实现我的目标最优雅的方式是什么?

我能想到的唯一方法是计算所有平均先前查询,并将其作为Pool 的新属性插入到数据库中,这样控制器就变成了:

# app/controllers/pool_controller.rb

  def index
    @user = current_user
    @pools = @user.pools
    render json: @pools, only: [:ticker, :id, :average]
  end

但我想知道,如果我想避免大规模计算来更新数据库添加和 :average 属性到每个池,我该怎么做。即使可能是最好的解决方案,而不是计算每个查询的平均值?

【问题讨论】:

    标签: ruby-on-rails json api


    【解决方案1】:

    尝试在 pool.rb 中编写一个名为 average 的方法,并在该方法中编写逻辑,

    在controller的index方法中这样写

    render json: @pools, only: [:ticker, :id, :average], methods: :average
    

    【讨论】:

      猜你喜欢
      • 2018-01-02
      • 2015-10-18
      • 1970-01-01
      • 1970-01-01
      • 2016-04-24
      • 2017-04-20
      • 2017-08-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多