ActiveRecord to_json:有条件地包括关联

时间:2012-04-25 14:30:53

标签: ruby-on-rails

当我在模型上使用.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 ==&#39;什么的条形实例?&#39;

我希望能有条件地拉入条形实例,或者甚至使用范围来限制json输出中包含的条形。

2 个答案:

答案 0 :(得分: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)

答案 1 :(得分:0)

也许使用像json_builder https://github.com/dewski/json_builder

这样的东西