在Rails中有三个多对多关系,如果给出另外两个,我怎么能找到一个呢?

时间:2012-02-17 21:09:14

标签: ruby-on-rails activerecord

我有3个模特。

class Team < ActiveRecord::Base
  ...
  has_many :seasons_teams, :dependent => :destroy                          
  has_many :seasons, :through => :seasons_teams
  has_and_belongs_to_many :players
  ...
end

class Season < ActiveRecord::Base
  ...
  has_many :players_seasons, :dependent => :destroy
  has_many :players, :through => :players_seasons
  has_many :seasons_teams, :dependent => :destroy
  has_many :teams, :through => :seasons_teams
  ...
end

class Player < ActiveRecord::Base
  ...
  has_many :players_seasons, :dependent => :destroy
  has_many :seasons, :through => :players_seasons
  has_and_belongs_to_many :teams
  ...
end

将会有验证,以确定任何一名球员每个赛季最多只能有一支球队。

我正在寻找一种有效的方法来获得任何一个赛季的球员队伍,即:

@player.team(@season)

谢谢!

3 个答案:

答案 0 :(得分:1)

我认为这样的事情应该有效:

@player.teams.joins( :seasons ).where( :season_id => @season.id ).first

要获得您正在寻找的简洁语法,您可以在范围内使用它,例如:

class Team < ActiveRecord::Base
  scope :for_season, lambda do |season|
    joins( :seasons ).where( :season_id => season.id )
  end
  # ...
end

class Player < ActiveRecord::Base
  # ...

  def team season
    teams.for_season( season ).first
  end
end

@player.team @season
# => #<Team:0x...>

答案 1 :(得分:0)

@player.teams.find_by_season_id(@season.id)

答案 2 :(得分:0)

看起来你的团队成员中有错字或错误。我想你应该:

has_many :seasons, :through => :seasons_teams