2010-07-06 67 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