Title: Using to_json to include nested information from a method
Tags: ruby-on-rails;json
Question: I have a nested method that I'd like to output via to_json:
Venue has a method called published_events that returns events that are published:
def published_events
events_array = []
self.events.each do |event|
if event.published
events_array << event
end
end
events_array
Event has a to_param method on it that I'd like to include in the json rendering of Venue:
format.json { render :json =&gt; @venue.to_json(:methods =&gt; :published_events =&gt; {:include =&gt; :to_param}) }
This, of course, doesn't work to include the to_param method of events. Is there another way I should go about this or will I need to build my own json? Is there a way in the published_events method that I can include the to_param method?

Here is the accepted answer: @venue.to_json(:include =&gt; {:published_events =&gt; {:method =&gt; :to_param}})
Comment for this answer: Wow... that worked (did have to change it to ":methods" pluralized)! Can't believe I missed it! :D


{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 1, 'CommentCount': 0, 'ContentLicense': 'CC BY-SA 3.0', 'CreationDate': '2013:00:04/16/13', 'FavoriteCount': None, 'PostTypeId': 1, 'Tags': '<ruby-on-rails><json>', 'Title': 'Using to_json to include nested information from a method', 'ViewCount': 2908, 'id': 16041879, 'user_AboutMe': '<p>about me</p>\n', 'user_AccountId': 255520.0, 'user_DisplayName': 'Jayson Lane', 'user_Reputation': 2810.0, 'user_Views': 145.0, 'user_id': 535632.0}}