2012-03-22 34 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

相關問題