加入一张桌子两次

时间:2013-08-12 13:53:28

标签: ruby-on-rails

我的数据库架构:

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])

2 个答案:

答案 0 :(得分: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只能匹配匹配。

答案 1 :(得分:0)

匹配模型中的belongs_to,而不是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

现在我可以在我的视图中使用tournament.home_team.name