2012-05-30 3 views
4

그래서 훌륭한 granchildren 모델에 대한 쿼리를 수행하려고합니다. 관계는 ... 그래서입니다레일스 3 그레이트 그랜트 레코드를 ActiveRecord 콜렉션으로 검색

토너먼트>> 매치 경기> 선수

및 토너먼트 모델 : 현재 나는 모든 위대한 큰 손자 기록을 검색하는 무슨

class Tournament < ActiveRecord::Base 
    has_many :competitions, :dependent => :destroy 
    has_many :matches, :through => :competitions 
    has_many :players, :through => :matches 

end 

은 다음과 같습니다

@results = @tournament.competitions.collect{|b| b.matches.collect{|c| c.players.with_win_count}}.flatten 

그러나이 문제는 배열을 반환합니다. 내가하려는 것은 사용자 입력을 기반으로 동적 쿼리를 작성하는 것이며, 플레이어 테이블은 본질적으로 모든 일치에 대한 결과 풀이며 사용자는보고 싶은 것만 필터링 할 수있는 옵션이 있습니다. 필자는 결국 사용자 입력에 따라 상당히 복잡한 (잠재적으로 복잡한) 쿼리와 추가 절을 배열에서 수행 할 수 없게됩니다. 당신이이 일을하기위한 것입니다 방법의 더 나은 아이디어를 제공하기 위해, 여기 내 코드 ...

def results 
    @tournament = Tournament.find(params[:id]) 
    @results = @tournament.all_great_grandchildren 
    @results.where(params[:player_condition1]) if params[:player_condition1] 
    @results.where(params[:player_condition2]) if params[:player_condition2] 
    @results.where(params[:player_condition3]) if params[:player_condition3] 

    if params[:match_condition] 
    #Join to match table so we can query the match fields 
    @results.join(:match) 
    @results.where(params[:match_condition]) 
    end 
    .... 
    @results.order(params[:order]) if params[:order] 
end 

배열없이 주어진 대회의 큰 손자 (플레이어)의 모든 레코드를 찾을 수있는 방법이있다 그래서 나는 기록을 계속 조절할 수 있습니까?

답변

8

위의 연결을 사용하여 설정 한 경우 @tournament.players을 호출하면 문제가 해결됩니다.

+0

GAH를, 그렇게 간단했다! 나는 그것을 발견하지 못했다 ... 궁금해서 나는 @results = Player.join (: match => : competition) @results = @ results.where ("competition.tournament_id = ? ", @ tournament.id)'그러나 당신의 방법은 깨끗해 보입니다. – Noz

+0

당신을 진심으로 환영합니다. :) – Chamnap

1

Chamnap이 가지고 있습니다. 모델에 "has_many"와 "belongs_to"연관을 정의하는 이유는 연관 모델에 쉽게 접근 할 수있게 해주기 위해서입니다. 당신이 대회라는 대회 객체가있을 때

그래서, 당신은

competitions = tournament.competitions 
matches = tournament.matches 
players = tounaments.players 

당신은 또한 플레이어 객체로 시작, 반대 방향으로 갈 수 할 수 있습니다. 예 : matches = player.matches

Active Record를 사용하면 연결을 처리 할 때 수동 조인 또는 원시 SQL 모델 호출을 할 필요가 없습니다. Actice 레코드 협회 가이드의 빠른 읽게

http://guides.rubyonrails.org/association_basics.html

관련 문제