Challenge - 5 Problems
JSON Rendering Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate2:00remaining
What is the JSON output of this Rails controller action?
Consider this Rails controller action rendering JSON. What will be the exact JSON output sent to the client?
Ruby on Rails
def show user = User.new(id: 1, name: "Alice", admin: false) render json: { id: user.id, name: user.name } end
Attempts:
2 left
💡 Hint
Look at the hash passed to render json: and what keys it contains.
✗ Incorrect
The render json: method converts the given hash to JSON. Only id and name keys are included, so the output JSON has only those fields.
📝 Syntax
intermediate2:00remaining
Which option correctly renders a JSON array of user names in Rails?
You want to render JSON with an array of user names from a list of User objects. Which code snippet produces the correct JSON output?
Ruby on Rails
users = [User.new(name: "Alice"), User.new(name: "Bob")] render json: ???
Attempts:
2 left
💡 Hint
You want a simple array of strings, not an array of hashes.
✗ Incorrect
users.map(&:name) returns an array of names like ["Alice", "Bob"], which renders as a JSON array of strings.
🔧 Debug
advanced2:00remaining
Why does this Rails JSON render raise an error?
This code raises an error when rendering JSON. What is the cause?
Ruby on Rails
def index
users = User.all
render json: { users: users }
endAttempts:
2 left
💡 Hint
Think about how ActiveRecord objects convert to JSON by default.
✗ Incorrect
ActiveRecord collections need to be serialized or converted to arrays/hashes before rendering JSON. Passing them directly can cause errors or unexpected output.
❓ state_output
advanced2:00remaining
What JSON output results from this Rails view with Jbuilder?
Given this Jbuilder template, what JSON will be rendered?
Ruby on Rails
json.array! @users do |user| json.id user.id json.name user.name end
Attempts:
2 left
💡 Hint
array! creates a JSON array directly from the block.
✗ Incorrect
json.array! builds a JSON array of objects with id and name keys for each user.
🧠 Conceptual
expert3:00remaining
Which option best explains how Rails handles JSON rendering with ActiveModel::Serializers?
When using ActiveModel::Serializers in Rails, how does the JSON rendering process work?
Attempts:
2 left
💡 Hint
Think about how serializers customize JSON output.
✗ Incorrect
ActiveModel::Serializers lets you specify exactly which attributes and relationships to include in JSON. Rails uses the serializer instead of default to_json.