0

我的数据库架构:

tournaments(id, ...)
teams(tournament_id, id, ...)
matches(tournament_id, id, team_id_home, team_id_away, ...)

楷模:

class Tournament < ActiveRecord::Base
    has_many :teams, dependent: :destroy
    has_many :matches, dependent: :destroy
    ...
end

class Team < ActiveRecord::Base
    belongs_to :tournament
    ...
end

class Match < ActiveRecord::Base
    belongs_to :tournament
    has_many :teams
    ...
end

我想在我的视图中有以下数据:

match_id  team_id_home  team_id_away  team_id_home_name  team_id_away_name

因此,我正在就以下查询寻求帮助(我正在尝试获取团队的名称,但在加入时遇到问题):

@matches = @tournament.matches.where(:tournament => @tournament).joins(:teams).paginate(page: params[:page])
4

2 回答 2

0

我对 Rails 很陌生,但你应该能够像这样设置你的关联:(从记忆中)

class Match < ActiveRecord::Base
    belongs_to :tournament
    has_one :home_team, :class_name => "Team", :foreign_key => "team_id_home"
    has_one :away_team, :class_name => "Team", :foreign_key => "team_id_away"
end

#####

m = Match.first
m.away_team.team_name
m.home_tam.team_name

或者在你的情况下:

@matches = @tournament.matches.paginate(page: params[:page])

我认为您不需要 where 函数: has_many 关联告诉 rails 只提取匹配的匹配项。

于 2013-08-12T13:59:20.287 回答
0

它是belongs_to,而不是Match 模型中的has_one。

class Match < ActiveRecord::Base
    belongs_to :tournament
    belongs_to :home_team, :class_name => "Team", :foreign_key => "team_id_home"
    belongs_to :away_team, :class_name => "Team", :foreign_key => "team_id_away"
end

class Team < ActiveRecord::Base
    belongs_to :tournament
    has_many :matches
end

现在我可以在我的视图中使用锦标赛.home_team.name

于 2013-08-12T19:22:40.703 回答