Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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!