2010-05-18 71 views
0

我有一个模型是这样的:条件关系

Stem 
    -id 
    -etc 

然后,我有

Stemrelation 
    -stem_id 
    -related_stem_id 
    -active 

我可以得到下面的关系相关的茎

class Stem < ActiveRecord::Base 
    has_many :stemrelations 
    has_many :related_stems, :through => :stemrelations 
end 

class Stemrelation < ActiveRecord::Base 
    belongs_to :stem 
    belongs_to :related_stem, :class_name => "Stem", :foreign_key => "related_stem_id" 
end 

但现在我只想得到积极的关系。

我尝试添加这对干型号:

has_many :active_related, :through => :stemrelations, :source => :related_stem, :conditions => {:active => true} 

但becasue它试图检查活动标志的干模型,而不是stemrelation这给了我一个错误。我在这里改变什么?

谢谢!

回答

1

你是否确实需要条件关联。在这里可以named_scope适合:

class Stem < ActiveRecord::Base 
    has_many :stemrelations 
    has_many :related_stems, :through => :stemrelations 

    named_scope :active, :conditions => {:active => true} 
end 

您可以使用它像这样:

Stem.first.related_stems.active 
0

的条件,则必须使用SQL语法。