开发者

Conditional relation

开发者 https://www.devze.com 2022-12-30 21:01 出处:网络
I\'ve got a model like this: Stem -id -etc And then I have Stemrelation -stem_id -related_stem_id -active I can get the related stems with th开发者_StackOverflowe following relations

I've got a model like this:

Stem
  -id
  -etc

And then I have

Stemrelation
  -stem_id
  -related_stem_id
  -active

I can get the related stems with th开发者_StackOverflowe following relations

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

But now I'd only like to get the active relations.

I tried adding this to the Stem model:

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

but this gives me an error becasue it tries to check the active flag on the stem model instead of the stemrelation. What do I change here?

Thanks!


Are you shure that you need conditional association. May be named_scope fits here:

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

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

You can use it like this:

Stem.first.related_stems.active


for the conditions, you must use the SQL SYNTAX.

0

精彩评论

暂无评论...
验证码 换一张
取 消