我有这些模型: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