2012-03-22 32 views
0

我有这些模型:Rails - 更智能的方法来做到这一点?

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语句。

感谢

回答

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是不是一个块?对。但红宝石自动调用to_proc方法上的符号。

to_proc方法被定义这样的:

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

这看起来很接近,但'sport_name'在'teams'上。该查询尝试'players.sport_name'。有没有办法改变它? – 2012-03-22 18:23:50

+0

我编辑了我的答案,我认为这应该工作。我认为如果列名中没有歧义,那么Rails正在处理这些东西。显然不是。 – Robin 2012-03-22 19:30:05

+0

完美,谢谢!你能解释一下'map(&:firstName)'的作用吗?具体来说,'&'部分? – 2012-03-22 20:42:38

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

+0

什么会这让我? – 2012-03-22 18:24:04

相关问题