views:

23

answers:

1

In Rails apps, I find myself placing a lot of nested :include => statements in my JSON rendering code to include objects with relationships(direct and indirect) to the root object. Is there any way to get to_json(or a similar method) to automatically include all related objects without explicitly specifying them?

+2  A: 

Sure, override the #to_json method:

class Post < ActiveRecord::Base
   def to_json(options={})
     super(options.merge(:include => :comments, :methods => [:arbitrary_field]))
   end
end
François Beausoleil
This won't include arbitrary fields though. I want every possible option to be included, not just `:comments`.
Mike
Check the latest version. Specify :methods to add arbitrary fields. See http://api.rubyonrails.org/classes/ActiveRecord/Serialization.html#M001873
François Beausoleil