Rails - 更聪明的方式加入?

时间:2012-03-22 17:56:36

标签: ruby-on-rails activerecord join

我有这些模特:

class Player < ActiveRecord::Base
  has_many :players_to_teams
  has_many :teams, through: :players_to_teams
end

class Team < ActiveRecord::Base
  has_many :players_to_teams
  has_many :players, through: :players_to_teams
end

class PlayersToTeam < ActiveRecord::Base
  belongs_to :player
  belongs_to :team
end

球队拥有运动类型(“足球”),球员拥有主场状态(“CA”)。

我想要一份来自加利福尼亚的每个足球运动员的名字列表。

SQL看起来像

SELECT p.FirstName 
FROM players AS p
INNER JOIN players_to_teams AS ptt
ON p.id = ptt.player_id 
INNER JOIN teams AS t 
ON t.id = ptt.team_id 
WHERE t.sport_name = "Football" AND p.home_state = "CA"

我唯一能想到的就是让所有的足球运动员fb_players = Sport.find_all_by_sport_nane("Football"),然后遍历所有fb_players.players并查看谁来自加利福尼亚,但这感觉比单个SQL语句慢

由于

2 个答案:

答案 0 :(得分:1)

试试:

Player.select("firstName").joins(:teams).where(:"teams.sport_name" => "Football", :home_state => "CA").map(&:firstName)

回答你的评论:

执行.map(&:firstName)就像做.map{ |player| player.firstName }一样。 基本上,&正在将Proc转换为块以传递给map方法。但:firstName不是块?!对。但是ruby会自动在符号上调用to_proc方法。

to_proc方法定义如下:

def to_proc
    proc { |obj, *args| obj.send(self, *args) }
end

答案 1 :(得分:0)

尝试has_and_belongs_to_many

class Player < ActiveRecord::Base
  has_and_belongs_to_many :teams, :join_table = "players_to_teams"
end

class Team < ActiveRecord::Base
  has_and_belongs_to_many :players, :join_table = "players_to_teams"
end

http://jonathanhui.com/ruby-rails-3-model-many-many-association