Rails,在两个不同的表上按相同名称的列排序

时间:2018-08-17 20:49:17

标签: sql ruby-on-rails join activerecord

我有一个模型Leagues :: FantasyPlayer,它具有一个多态变量player_entity,该变量可以是Players :: NflPlayer或Players :: TeamPlayer。

我正试图加载一个联盟的幻想球员,按“ average_draft_position”排序。两个表Player :: NflPlayer和Players :: TeamPlayer都有一列“ average_draft_position”。

这是我目前的尝试:

 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

问题在于,这将首先返回按average_draft_position排序的Players :: NflPlayer表,然后再按average_draft_position排序的Players :: TeamPlayer表-是否可以通过某种方式使两个不同表的结果交错?

谢谢!

1 个答案:

答案 0 :(得分:1)

这应该可以解决问题。

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