Luis C.
Luis C.

Reputation: 755

Rails4 + Json API : Increase detail of response

I'm a newbie on RoR (and Ruby). I need a little help about a json response (with Grape).

This is the sample:

    {
      events: [
           {
            'some data':'some data',
             place_id: 1
           }
      ]
    }

Now this is the result of Events.all in Rails, but I want to make for each event a query for the place, to have more data instead only id. I'm sure that new lambda function can help me, but for now I have no idea about to make it. I'm trying without success...

Thanks in advance

UPDATE

Desired result

{
          events: [
               {
                'some data':'some data',
                 place : {
                   id: 1,
                   name: 'Blablabla'
               }
          ]
        }

Upvotes: 0

Views: 96

Answers (2)

Luis C.
Luis C.

Reputation: 755

    :events => events.as_json(include: :place)

This is a useful for my problem. After add belongs_to, obviously.

from http://api.rubyonrails.org/classes/ActiveModel/Serializers/JSON.html

Upvotes: 0

samuil
samuil

Reputation: 5081

Consider using ActiveModelSerializers which allows you to define how your models should be serialized in a manner similar to ActiveRecord DSL (e.g. your problem would be solved by defining that event has_one :place)

Upvotes: 2

Related Questions