2012-04-25 65 views
5

我試圖找到一種方法來在模型上使用.to_json時有條件地包含關聯模型。ActiveRecord to_json:有條件地包含關聯

在一個簡單的例子,假設以下兩種模式:

class Foo < ActiveRecord::Base 
    has_many :bars 
end 

class Bar < ActiveRecord::Base 
    belongs_to :foo 
    attr_accessible :bar_type 
end 

我目前有:

f = Foo.find "3" 
j = f.to_json(:include => { :bars => {:some, :attributes}} 

和工作原理。我需要找到的方法是隻包含bar_type =='什麼?

我希望有一種方法來有條件地拉動條形實例,或者甚至可以使用範圍來限制包含在json輸出中的條形。也許

回答

3

如果條件不改變,你可以這樣做:

class Foo < ActiveRecord::Base 
    has_many :bars 
    has_many :what_bars, :class_name=>"Bar", 
         :foreign_key=>:foo_id, 
         :conditions=>"bars.bar_type = 'what'" 
end 

f = Foo.find "3" 
j = f.to_json(:include => :what_bars) 
+0

有趣的方法。我會試一試並回復你:) – jaydel 2012-04-25 18:37:55