user483040
user483040

Reputation:

ActiveRecord to_json: conditionally include associations

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.

Upvotes: 5

Views: 1113

Answers (2)

klochner
klochner

Reputation: 8125

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)

Upvotes: 3

sailor
sailor

Reputation: 8044

Maybe by using something like json_builder https://github.com/dewski/json_builder

Upvotes: 0

Related Questions