具有has_many通过关联的范围

时间:2010-07-06 09:50:16

标签: ruby-on-rails

我有2个模型Widget和Feature,它们使用WidgetFeature模型有很多关联。

  class Widget < ActiveRecord::Base
    has_many :widget_features
    has_many :features, :through => :widget_features
  end

  class WidgetFeature < ActiveRecord::Base
    belongs_to :feature
    belongs_to :widget
    attr_accessible :children_features, :widget_id, :feature_id
  end

 class WidgetFeature < ActiveRecord::Base
   belongs_to :feature
   belongs_to :widget
   attr_accessible :children_features, :widget_id, :feature_id
 end

我有一个widget_id。

所以我做了Widget.find_by_id(widget_id)

现在,我想查找此小部件的所有功能widget_features.children_features IS NULL

我不知道该怎么做,帮助我。

3 个答案:

答案 0 :(得分:0)

尝试

@widget = Widget.find_by_id(widget_id)
@features = @widget.features.conditions("widget_features.children_features IS nil")

EDITED

参考this

has_many :features, :through => :widget_features, :conditions=>["widget_features.children_features is nil"]

然后

@widget = Widget.find_by_id(widget_id)
@features = @widget.features

答案 1 :(得分:0)

Feature.all(:joins => :widget_features, :conditions => ["widget_id = ? and children_features is null", some_id])

答案 2 :(得分:0)