ActiveRecord to_json: conditionally include associations

ruby-on-rails

Solution

If the conditions don't change, you could do this:

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)

Problem

I'm trying to find a way to conditionally include associated models when I use .to_json on a model. In a simplified example, assume the following two models: ``` class Foo < ActiveRecord::Base has_many :bars end class Bar < ActiveRecord::Base belongs_to :foo attr_accessible :bar_type end ``` I currently have: ``` f = Foo.find "3" j = f.to_json(:include => { :bars => {:some, :attributes}} ``` and this works. What I need to find a way to do is only include bar instances that have bar_type == 'what?' I'm hoping there's a way to conditionally pulling in the bar instances, or perhaps even use a scope to limit the bars that are included in the json output.

Original source