【问题标题】:How do I include only last record in the response that contains associated records in Ruby On Rails?如何在包含 Ruby On Rails 中关联记录的响应中仅包含最后一条记录?
【发布时间】:2016-10-12 23:48:49
【问题描述】:

此功能有效。但是,而不是包括所有回合。我只需要包括最后一个。我该怎么做?我研究过使用 :scope 但没有发现任何有用的东西。请帮忙,这让我发疯了!

def get_games_list
    Rails.logger.info("get_games_list".colorize(:color => :white, :background => :blue))

    player_1_games = Game.includes(:rounds, :player_2).where(:player_1_id => params[:player_id], :is_valid => true)
    player_2_games = Game.includes(:rounds, :player_1).where(:player_2_id => params[:player_id], :is_valid => true)

    render json: {
      error_code: ERROR_NOERROR, 
      status: "ok", 
      player_1_games: player_1_games.as_json(
        :include => {
          :player_2 => {
              :only => [:id, :user_name]
          },
          :rounds => { 
            :only => [:id, :playing_player_id]
          }
        }
      ), 
      player_2_games: player_2_games.as_json(
        :include => {
          :player_1 => {
              :only => [:id, :user_name]
          },
          :rounds => { 
            :only => [:id, :playing_player_id]
          }
        }
      )
    }
    return
  end

【问题讨论】:

    标签: ruby-on-rails json activerecord


    【解决方案1】:

    您可以在 Game 模型中创建 :last_round has_one 关联。

    class Game < ApplicationModel
      # ...
      has_one :last_round, -> { order(round_date: :desc) }, class_name: 'Round'
      # ...
    end
    

    【讨论】:

      猜你喜欢
      • 2012-11-19
      • 1970-01-01
      • 1970-01-01
      • 2013-06-05
      • 2021-12-26
      • 1970-01-01
      • 1970-01-01
      • 2020-08-28
      • 1970-01-01
      相关资源
      最近更新 更多