5

当我在模型上使用 .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 == 'what?' 的 bar 实例

我希望有一种方法可以有条件地拉入 bar 实例,或者甚至使用范围来限制 json 输出中包含的 bar。

4

2 回答 2

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)
于 2012-04-25T16:03:47.580 回答
0

也许通过使用类似 json_builder https://github.com/dewski/json_builder

于 2012-04-25T14:58:39.747 回答