레일

2011-03-20 4 views
1

그래서,이 개 모델을 가지고 관련 항목을 찾을 수 has_many :레일

class Match < ActiveRecord::Base 
    has_many :rounds 
    has_many :participations 
    has_many :players, :through => :participations 
    belongs_to :clan_1, :class_name => "Clan", :foreign_key => "clan_1_id" 
    belongs_to :clan_2, :class_name => "Clan", :foreign_key => "clan_2_id" 
    belongs_to :winner, :class_name => "Clan", :foreign_key => "winner_id" 
    belongs_to :league 
    belongs_to :tournament 

    validates :clan_1_id, :presence => true 
    validates :clan_2_id, :presence => true 

    scope :by_league, lambda { |league| where("league_id == ?",league.id) } 
    scope :by_tournament, lambda { |tournament| where("tournament_id == ?",tournament.id) } 
    scope :played, where("played is not NULL") 
    scope :not_played, where("played is NULL") 


end 


class Clan < ActiveRecord::Base 
    has_many :players 
    has_many :rounds_won, :class_name => "Round", :foreign_key => "winner_id" 
    has_many :rounds_blue, :class_name => "Round", :foreign_key => "clan_blue_id" 
    has_many :rounds_purple, :class_name => "Round", :foreign_key => "clan_purple_id" 
    has_many :matches_won, :class_name => "Match", :foreign_key => "winner_id" 
    has_and_belongs_to_many :leagues 
    has_and_belongs_to_many :tournaments 


    def matches 
    Match.where("clan_1_id = ? OR clan_2_id = ?",self.id, self.id) 
    end 

    def matches_lost 
    matches.where("winner_id != ?", self.id) 
    end 

    def matches_drawn 
    matches.played.where("winner_id is NULL") 
    end 

end 

을 나는 경기에 참가한 모든 종족을 가져 싶다.

답변

2

:이 테스트되지 않은 상태입니다

class Clan < ActiveRecord::Base 
    scope :participated_in_match, includes(:one_matches, :two_matches).where("matches.id IS NOT NULL") 
end 

:

class Match < ActiveRecord::Base 
    belongs_to :clan_1, :class_name => "Clan" 
    belongs_to :clan_2, :class_name => "Clan" 
end 

class Clan < ActiveRecord::Base 
    has_many :one_matches, :class_name => 'Match', :foreign_key => :clan_1_id 
    has_many :two_matches, :class_name => 'Match', :foreign_key => :clan_2_id 
end 

그런 다음이 범위를 추가 할 수 있습니다 예상치 못한 결과가 발생하면 알려 주시기 바랍니다.

0

아주 간단 :

당신은 그것을 생각에 걸쳐있어
model_two_object = Model_2.first # For clarity only, change to suit your needs 
model_two_object.models_1 
3

. Rails를 사용하면이 작업을 매우 쉽게 할 수 있습니다.

class Comment < ActiveRecord::Base 
    belongs_to :post 
end 

class Post < ActiveRecord::Base 
    has_many :comments 
end 

@post.comments 

당신은 "MODELNAME"_id (예 : post_id를) 자동으로 외래 키를 연결하여 레일과 귀하의 코멘트 테이블의 열이있는 경우.

@ model1.model2를 호출하면 @ model1이 model1 객체의 인스턴스라고 가정하면됩니다.

쿼리를 직접 연결하려면 where() 메서드를 사용할 수 있습니다. 당신은 당신이 이용할 수있는 약간 포함하여 협회() 범위에서를 변경하는 경우

@comments = Comment.where(:post_id => some_id) 
+0

내 첫 번째 의사 코드가 명확하지 않아 실제 코드로 문제를 편집하여 내 문제를 잘 보여줍니다. – methyl