我有这些模型:
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球队有运动类型("Football"),球员有主场状态("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语句要慢得多。
谢谢
发布于 2012-03-23 02:06:17
试一试:
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发布于 2012-03-23 02:01:51
试试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"
endhttp://jonathanhui.com/ruby-rails-3-model-many-many-association
https://stackoverflow.com/questions/9827868
复制相似问题