2010-07-06 63 views
0

我有2个模型的小部件和功能,有一个有很多通过使用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(WI​​DGET_ID)

现在我想找到这个小工具,其中widget_features.children_features IS NULL所有功能。

我不知道如何做到这一点,帮助我。

+1

您粘贴WidgetFeature两次请提供功能模型 – Salil 2010-07-06 10:06:47

回答

0

我为named_scope工作,发现了一个优雅的解决方案。所以,我在这里发布它,以便其他人坚持相同的问题也可以得到帮助。 我的解决方案为您提供了一种访问具有很多直通关联的连接模型的任何列的方法。

下面是我的上述问题的解决方案:

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

    def leaf_features 
    widget_features.leaf_features.map{|widget_feature|widget_feature.feature} 
    end 
end 

class WidgetFeature < ActiveRecord::Base 
    named_scope :leaf_features, :conditions => 'children_features IS NULL' 
    belongs_to :feature 
    belongs_to :widget 
    attr_accessible :children_features, :widget_id, :feature_id 
end 

现在,Widget.find_by_id(widget_id).leaf_features 会给你只是这些功能,其中 children_features column is NULL

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 
+0

它不起作用。 我得到一个错误 未定义的方法'条件'为#<类:0x7fee245df970> 这意味着条件不是一种方法。 – 2010-07-06 10:37:27

+0

@Jatin: - 检查我编辑的答案。 – Salil 2010-07-06 11:23:06

+1

- 它仍然不起作用,并给我一个SQL错误。 Mysql ::错误:您的SQL语法中有错误;检查与您的MySQL服务器版本相对应的手册,以便在'nil'附近使用正确的语法))''在第1行:SELECT'features'。* FROM'features' INNER JOIN'widget_features' ON'features'.id =' widget_features'.feature_id WHERE((widget_features'.widget_id = 1)AND((widget_features.children_features is nil))) – 2010-07-06 19:00:45

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

获得奖励积分,请使用named_scope – 2010-07-06 12:51:34