2011-03-20 66 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