Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 578
Jayson Lane Avatar asked Apr 16 '13 16:04

Jayson Lane


People also ask

What is nested JSON object?

We need to find some values from that nested collections of details. That collection is known as the JSON object and the information inside object are known as nested JSON object. Example 1: We create the nested JSON objects using JavaScript code.

How do I navigate to a specific node in a JSON?

Instead, we can use the tree structure of a JSON so that we can navigate to any node via a path. We have already covered parsing a simple JSON Object, Nested JSON Object and simple JSON Array as JsonNode previously.

What is a JSON array in Jackson?

A JSON array may be a collection of JSON objects or JSON arrays. Below is also a valid example of a JSON array. We need to use class ObjectMapper provided by Jackson API.

What library do I use to create JSON?

In the .net world, the go to library is Newtonsoft.Json, so we will be using that. For other methods of creating Json take a look here for an idea of how easy the Newtonsoft solution actually is.


1 Answers

 @venue.to_json(:include => {:published_events => {:method => :to_param}})
like image 120
manoj Avatar answered Nov 10 '22 14:11

manoj