nebulus nebulus - 1 month ago 10
JSON Question

How do I include only last record in the response that contains associated records in Ruby On Rails?

this function works. However, instead of including all the rounds. I just need to include the last one. How would I do it? I looked into using :scope but haven't found anything useful. Please help, it's driving me nuts!

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

Answer

You could create a :last_round has_one association in the Game model.

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