Rails 3在一个查询中包含多个表

时间:2011-04-01 21:11:58

标签: ruby-on-rails ruby activerecord

我在铁路应用程序上进行锦标赛。我有三个模型正在使用此查询:

class Player < ActiveRecord::Base
  validates :name, :uniqueness => true
  has_and_belongs_to_many :tournaments

class Tournament < ActiveRecord::Base
  belongs_to :tournament_type
  has_and_belongs_to_many :players
  has_many :player_matches, :dependent => :destroy

class PlayerMatch < ActiveRecord::Base
  belongs_to :player_one, :class_name => "Player", :foreign_key => "player_one"
  belongs_to :player_two, :class_name => "Player", :foreign_key => "player_two"

在tournaments_controller的show动作中,我调用以下查询:

Tournament.where(:id => params[:id]).includes(:player_matches, :players).first()

虽然锦标赛和player_matches是在一次加入中完成的,但是玩家会被单独查询,因为我的代码依赖于他们:

Player Load (0.4ms)  SELECT `players`.*, t0.tournament_id as the_parent_record_id FROM `players` INNER JOIN `players_tournaments` t0 ON `players`.id = t0.player_id WHERE (t0.tournament_id = 14)
Player Load (0.2ms)  SELECT `players`.* FROM `players` WHERE `players`.`id` = 5 LIMIT 1
Player Load (0.2ms)  SELECT `players`.* FROM `players` WHERE `players`.`id` = 9 LIMIT 1
Player Load (0.2ms)  SELECT `players`.* FROM `players` WHERE `players`.`id` = 1 LIMIT 1
Player Load (0.1ms)  SELECT `players`.* FROM `players` WHERE `players`.`id` = 8 LIMIT 1
Player Load (0.1ms)  SELECT `players`.* FROM `players` WHERE `players`.`id` = 3 LIMIT 1
Player Load (0.1ms)  SELECT `players`.* FROM `players` WHERE `players`.`id` = 2 LIMIT 1
Player Load (0.1ms)  SELECT `players`.* FROM `players` WHERE `players`.`id` = 7 LIMIT 1
Player Load (0.1ms)  SELECT `players`.* FROM `players` WHERE `players`.`id` = 6 LIMIT 1
Player Load (0.1ms)  SELECT `players`.* FROM `players` WHERE `players`.`id` = 4 LIMIT 1

我如何更改它,以便在一个查询中全部拉出来?

1 个答案:

答案 0 :(得分:11)

Tournament.where(:id => params[:id]).includes([{:player_matches => :player_one}, :players]).first()

这应该可以解决问题。实际上,数组表示法和散列表示法的组合起初有点混乱,但是使用控制台并且你会发现哪种语法不会崩溃:)