← Back to Upcase

API with associations: rendering json

(Brian Dear) #1

Given the following:

A user fills out a Situation form, they add some Emotions and then they add some Places. As a user, I want to view my list of situations and see an individual situation from a native mobile app (i.e. via an API call/JSON response to the Rails app.)

Here are the associations:
A Situation Model. An Emotion Model that belongs to Situation. A Places model that is an HABTM with Situation.

I need to render the JSON for the show action for Situation, however simply using respond_with situation only renders out the specific fields for Situation and not the associated fields. I need to be able to call the show action and return the complete Situation.

How can I make the show action endpoint actually retrieve the complete situation (with it’s associated records) and not just the Situation by itself? Should I need to create a template with Jbuilder?

Here’s the relevant parts of the SituationsController. Note, using Decent Exposure, although that doesn’t (or shouldn’t) have an effect. This is also standard Rails4/ActiveRecord.

class SituationsController < ApplicationController


  expose(:situations) { current_user.situations }
  expose(:situation, attributes: :situation_params)

  respond_to :json

  def index
    respond_with situations

  def show
    respond_with situation


(Brian Dear) #2

Not to answer my own question, but the following seems to work:

def show
  respond_with situation.to_json(include: [:emotions, :places])

Are there any problems with that approach?

(Pedro Moreira) #3

Hi @briandear, if you don’t see a situation where you might need to further modify the response, I don’t think there is a problem.

As the saying goes, the only thing you can be sure is that things will change :), so I think adding a serializer would probably be your best bet.