私はこれらのモデルを持っている: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」)を有します。
カリフォルニアの各選手のファーストネームのリストが必要です。
私が考えることができる唯一のことは、fb_players.players
のすべてを反復処理し、カリフォルニア者を確認、その後、すべてのサッカー選手fb_players = Sport.find_all_by_sport_nane("Football")
を得ることですが、それはちょうど道遅く感じ
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"
のようにSQLが見えます1つのSQL文よりも
おかげ
これは近いようですが、 'sports_name'は' teams'にあります。このクエリは 'players.sport_name'を試みます。それを変える方法はありますか? –
私は私の答えを編集しました。これはうまくいくと思います。私は列名にあいまいさがなければ、レールはこのようなものを扱っていたと思った。どうやらない。 – Robin
パーフェクト、ありがとう! 'map(&:firstName)'が何をしているのか説明できますか?具体的には、 '&'部分は? –