Nathan Lauer
Nathan Lauer

Reputation: 391

Rails, order by same-named column on two different tables

I have a model Leagues::FantasyPlayer which has a polymorphic variable player_entity which is either a Players::NflPlayer or Players::TeamPlayer.

I'm attempting to load a league's fantasy players, sorted by "average_draft_position." Both tables Players::NflPlayer and Players::TeamPlayer have a column "average_draft_position."

Here is my current attempt:

 fantasy_players = paginate Leagues::FantasyPlayer.includes(player_entity: :team).
      joins("LEFT JOIN players_nfl_players ON leagues_fantasy_players.player_entity_id = players_nfl_players.id AND leagues_fantasy_players.player_entity_type = 'Players::NflPlayer'").
      joins("LEFT JOIN players_team_players ON leagues_fantasy_players.player_entity_id = players_team_players.id AND leagues_fantasy_players.player_entity_type = 'Players::TeamPlayer'").
      where(available: true, conference_id: conference_id,league_id: league_id).
      order("players_nfl_players.average_draft_position, players_team_players.average_draft_position"), per_page: 15

The problem is that this returns the Players::NflPlayer table sorted by average_draft_position first, and then Players::TeamPlayer table sorted be average_draft_position afterwards - is there some way I can have the results from the two different tables interleaved?

Thank you!!

Upvotes: 0

Views: 349

Answers (1)

sfate
sfate

Reputation: 155

This should do the trick.

.order('COALESCE(players_nfl_players.average_draft_position, players_team_players.average_draft_position) DESC')

Upvotes: 2

Related Questions