2

I'm looking for a way to shorten up the :include => :child inside a respond_with which generates json.

Here is an example, not sure if it is even possible, but I would like to find out.

In the controller:

@p = Parent.where('id = ?', params[:id])
respond_with(@p, :include => {:child1 => {}, :child2 => {}, :child3 => {:include => :grandchild1}})

Is there someway to include these all when I define the instance?

Maybe something like:

@p = Parent.includes(:child1, :child2, :child3, :grandchild1).where('id = ?', params[:id])
respond_with(@p)

Basically, I'm trying to DRY up my code ... I don't want to have to keep typing the include hash over and over ... Is there someway to just include all child objects in one call?

Thilo
  • 17,565
  • 5
  • 68
  • 84
ThaDick
  • 193
  • 2
  • 11
  • child1, child2 and child3 are associations of Parent? and grandchild1 is an association of child3? – Thilo Aug 05 '11 at 03:00
  • Yes Thilo, that would be correct. The children and grandchildren will vary depending on the model, so I was looking for something that could be used somewhat like a helper method ... But I'm having a tough time wrapping my head around it. – ThaDick Aug 08 '11 at 14:48

1 Answers1

5

ActiveRecord has an as_json method that defines how the object should be outputted as json. You can ovveride this method to include the associated children by default so something like this:

class Parent < ActiveRecord::Base

  # We went to display grandchildren by default in the output JSON
  def as_json(options={})
    super(options.merge(:include => {:child1 => {}, :child2 => {}, :child3 => {:include => :grandchild1}})
  end


end

That should let you clean up your controller a bit, you only need this:

@parent = Parent.find(params[:id])
respond_with @parent
Mario Visic
  • 2,653
  • 1
  • 22
  • 29
  • Hi Mario, I'm not sure that overriding the as_json method would work here. There could be any number of associations that I would be using. So, not sure that this would work, unless, I could enter the various children and grandchildren through the options, but that would be the same as using the original code, am I wrong? – ThaDick Aug 08 '11 at 14:50
  • If you're going to be using different options then yes you'll need to add them to the respond with statement like your original code above. – Mario Visic Aug 11 '11 at 11:18
  • you'd probably want `options.reverse_merge` there to have the intended effect. – sbeam Aug 07 '12 at 15:13