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.
If the conditions don’t change, you could do this: