ActiveRecord to_json: conditionally enable associations

I am trying to find a way to conditionally enable related models when I use .to_json for the model.

In a simplified example, suppose 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 it works. What I need to find a way to do this is to include only instances of the bar that have bar_type == 'what?'

I hope there is a way to conditionally pull out instances of the bar, or perhaps even use an area to limit the bars that are included in json output.

+5
source share
2 answers

If the conditions do not change, you can 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)
+3
source

Perhaps using something like json_builder https://github.com/dewski/json_builder

0

All Articles