2013-08-12 2 views
0

내 DB 스키마 가입하나 개의 테이블을 두 번

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 

을, I 다음 질문에 대한 도움을 요청합니다. (팀 이름을 얻으려고하는데 합류하는데 문제가 있습니다) :

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

답변

0

이 belongs_to, 일치 모델에서하지 has_one입니다. sqlite3를 ::되는 SQLException :

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 

지금은 내보기에

0

나는 레일 비교적 새로운 해요,하지만 당신은 설정이처럼 연결 할 수 있어야한다 :

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

:

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 

또는 귀하의 경우 (메모리에서 진행) 나는 where 함수가 필요 없다고 생각한다 : has_many 연관은 레일스가 일치하는 매치만을 끌어 오도록 지시한다.

+0

오류를 tournament.home_team.name을 사용할 수 없습니다 이러한 열 : teams.team_id_home를 "팀"SELECT * "팀" "팀의. "."team_id_home "=? ORDER BY "teams". "id"ASC LIMIT 1 – davor

관련 문제