如何在响应中包含仅包含Ruby On Rails中相关记录的最后一条记录?

时间:2016-10-12 23:48:49

标签: ruby-on-rails json activerecord

此功能有效。但是,而不是包括所有轮次。我只需要包括最后一个。我该怎么办?我调查了使用:范围,但没有找到任何有用的东西。请帮助,它让我疯了!

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

1 个答案:

答案 0 :(得分:1)

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

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