我有這些模型: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語句。
感謝
這看起來很接近,但'sport_name'在'teams'上。該查詢嘗試'players.sport_name'。有沒有辦法改變它? – 2012-03-22 18:23:50
我編輯了我的答案,我認爲這應該工作。我認爲如果列名中沒有歧義,那麼Rails正在處理這些東西。顯然不是。 – Robin 2012-03-22 19:30:05
完美,謝謝!你能解釋一下'map(&:firstName)'的作用嗎?具體來說,'&'部分? – 2012-03-22 20:42:38