ActiveRecord to_json:有条件地包括关联

jay*_*del 5 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 
Run Code Online (Sandbox Code Playgroud)

我目前有:

f = Foo.find "3"
j = f.to_json(:include => { :bars => {:some, :attributes}}
Run Code Online (Sandbox Code Playgroud)

这很有效.我需要找到的方法只包括bar_type =='what?'的bar实例.

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

klo*_*ner 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)
Run Code Online (Sandbox Code Playgroud)