Jayson Lane
Jayson Lane

Reputation: 2818

Using to_json to include nested information from a method

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

  end

Event has a to_param method on it that I'd like to include in the json rendering of Venue:

format.json { render :json => @venue.to_json(:methods => :published_events => {:include => :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?

Upvotes: 5

Views: 2941

Answers (1)

manoj
manoj

Reputation: 1675

 @venue.to_json(:include => {:published_events => {:method => :to_param}})

Upvotes: 10

Related Questions