Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

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!