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?
views:
23answers:
1
+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
2010-01-17 19:02:10
This won't include arbitrary fields though. I want every possible option to be included, not just `:comments`.
Mike
2010-01-17 22:27:53
Check the latest version. Specify :methods to add arbitrary fields. See http://api.rubyonrails.org/classes/ActiveRecord/Serialization.html#M001873
François Beausoleil
2010-01-18 23:39:08