2012-03-22 14 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」)を有します。

カリフォルニアの各選手のファーストネームのリストが必要です。

私が考えることができる唯一のことは、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文よりも

おかげ

答えて

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

これは近いようですが、 'sports_name'は' teams'にあります。このクエリは 'players.sport_name'を試みます。それを変える方法はありますか? –

+0

私は私の答えを編集しました。これはうまくいくと思います。私は列名にあいまいさがなければ、レールはこのようなものを扱っていたと思った。どうやらない。 – Robin

+0

パーフェクト、ありがとう! 'map(&:firstName)'が何をしているのか説明できますか?具体的には、 '&'部分は? –

0

するTry 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

この私を得るだろうか? –

関連する問題