2011-03-20 67 views
1

於是,找來2款:導軌的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 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 

然後你就可以添加此範圍:

class Clan < ActiveRecord::Base 
    scope :participated_in_match, includes(:one_matches, :two_matches).where("matches.id IS NOT NULL") 
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 2011-03-20 22:40:19