当我在模型上使用 .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。