Ruby Build a Rails API Coding the API Returning JSON

Using as_json challenge

The videos don't touch on the as_json method so I looked it up online and yet still baffled on how to pass this challenge. Attached is what I have so far..

monkeys_controller.rb
class MonkeysController < ApplicationController
  before_filter :find_monkey

  def show
    render json: @monkey.as_json(:include[:bananas])
  end

private
  def find_monkey
    @monkey = Monkey.find(params[:id])
  end
end

2 Answers

Almost, you have to pass a hash to as_json with :include as a key and the [Rails] association as the value. So you end up with:

def show
  render json: @monkey.as_json(include: :bananas)
end

You can also do it using the older hash rocket style (and with more explicit bracing) like:

def show
  render json: @monkey.as_json({:include => :bananas})
end

Assuming you found this, but for anyone else the documentation is here I use only: and except: more often in practice, for example, in not sending sensitive data without creating a bunch of temporary variables, but include is a close third. The same kind of syntax can also be nested in different use cases, e.g., Active Model Serialization.

Thanks George! The code I was referencing from had some unrelated complexities. It's nice to see a simple breakdown.

Chris Vukin
Chris Vukin
17,787 Points

This course seems to have a few of these issues where the course material does not cover things in the quiz. Thanks for posting this!