Bird
Raised Fist0
Ruby on Railsframework~20 mins

Serializers (Active Model Serializers) in Ruby on Rails - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Active Model Serializers Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What JSON output does this serializer produce?
Given the following serializer and model instance, what is the JSON output?
Ruby on Rails
class UserSerializer < ActiveModel::Serializer
  attributes :id, :name
  has_many :posts
end

user = User.new(id: 1, name: 'Alice')
post1 = Post.new(id: 10, title: 'Hello')
post2 = Post.new(id: 11, title: 'World')
user.posts = [post1, post2]

serialized = ActiveModelSerializers::SerializableResource.new(user).to_json
A{"user":{"id":1,"name":"Alice"}}
B{"id":1,"name":"Alice"}
C{"id":1,"name":"Alice","posts":[{"id":10,"title":"Hello"},{"id":11,"title":"World"}]}
D{"user":{"id":1,"name":"Alice","posts":[{"id":10,"title":"Hello"},{"id":11,"title":"World"}]}}
Attempts:
2 left
💡 Hint
Active Model Serializers wraps the output in a root key by default.
📝 Syntax
intermediate
1:30remaining
Which serializer code snippet is syntactically correct?
Identify the correct syntax for defining attributes and associations in an Active Model Serializer.
A
class ArticleSerializer &lt; ActiveModel::Serializer
  attributes :id, :title
  has_one :author
end
B
class ArticleSerializer &lt; ActiveModel::Serializer
  attribute :id, :title
  has_one :author
end
C
class ArticleSerializer &lt; ActiveModel::Serializer
  attributes :id :title
  has_one :author
end
D
class ArticleSerializer &lt; ActiveModel::Serializer
  attributes :id, :title
  has_one author
end
Attempts:
2 left
💡 Hint
Check the method names and syntax for attributes and associations.
🔧 Debug
advanced
2:30remaining
Why does this serializer raise an error?
Given this serializer code, why does it raise a NoMethodError when serializing?
Ruby on Rails
class CommentSerializer < ActiveModel::Serializer
  attributes :id, :content, :user_name

  def user_name
    object.user.name
  end
end

comment = Comment.new(id: 5, content: 'Nice post!')
serialized = ActiveModelSerializers::SerializableResource.new(comment).to_json
AThe method 'user_name' is not defined correctly; it should be a class method.
BThe comment object has no associated user, so 'object.user' is nil causing NoMethodError on 'name'.
CThe 'attributes' method cannot include custom methods like 'user_name'.
DThe serializer is missing 'has_one :user' declaration causing the error.
Attempts:
2 left
💡 Hint
Check if the associated user object exists before calling its methods.
❓ state_output
advanced
2:00remaining
What is the value of 'serialized' after running this code?
Consider this serializer with conditional attribute inclusion. What JSON does it produce when 'include_email' is false?
Ruby on Rails
class UserSerializer < ActiveModel::Serializer
  attributes :id, :name
  attribute :email, if: :include_email?

  def include_email?
    instance_options[:include_email] == true
  end
end

user = User.new(id: 2, name: 'Bob', email: 'bob@example.com')
serialized = ActiveModelSerializers::SerializableResource.new(user, include_email: false).to_json
A{"user":{"id":2,"name":"Bob","email":"bob@example.com"}}
B{"id":2,"name":"Bob"}
C{"user":{"id":2,"name":"Bob"}}
D{"id":2,"name":"Bob","email":"bob@example.com"}
Attempts:
2 left
💡 Hint
The email attribute is included only if 'include_email' option is true.
🧠 Conceptual
expert
3:00remaining
Which statement about Active Model Serializers caching is true?
Select the correct statement about how caching works in Active Model Serializers.
ACaching requires manual cache key management and does not expire automatically when object attributes change.
BCaching stores the entire serialized JSON output per object and automatically expires when the object changes.
CCaching is enabled by default and uses Rails fragment caching with no configuration needed.
DCaching only works for has_many associations, not for individual objects.
Attempts:
2 left
💡 Hint
Think about how cache keys and expiration are handled in serializers.

Practice

(1/5)
1. What is the main purpose of using Active Model Serializers in a Rails application?
easy
A. To handle database migrations automatically
B. To format and control how Rails models are converted to JSON responses
C. To manage user authentication and sessions
D. To style HTML views with CSS

Solution

  1. Step 1: Understand the role of serializers

    Serializers format model data into JSON, deciding which attributes to include.
  2. Step 2: Compare with other options

    Database migrations, authentication, and styling are unrelated to serializers.
  3. Final Answer:

    To format and control how Rails models are converted to JSON responses -> Option B
  4. Quick Check:

    Serializers format JSON = A [OK]
Hint: Serializers shape JSON output, not database or styling [OK]
Common Mistakes:
  • Confusing serializers with database migration tools
  • Thinking serializers handle user login
  • Assuming serializers style HTML pages
2. Which of the following is the correct way to define attributes in an Active Model Serializer?
easy
A. attributes :id, :name, :email
B. attribute :id, :name, :email
C. attrs :id, :name, :email
D. fields :id, :name, :email

Solution

  1. Step 1: Recall the syntax for attributes in serializers

    The correct method is attributes followed by symbols for each field.
  2. Step 2: Check other options

    attribute (singular), attrs, and fields are not valid methods in Active Model Serializers.
  3. Final Answer:

    attributes :id, :name, :email -> Option A
  4. Quick Check:

    Use plural 'attributes' method [OK]
Hint: Use plural 'attributes' to list fields in serializer [OK]
Common Mistakes:
  • Using singular 'attribute' instead of 'attributes'
  • Trying non-existent methods like 'attrs' or 'fields'
  • Forgetting to use symbols for attribute names
3. Given this serializer:
class UserSerializer < ActiveModel::Serializer
  attributes :id, :name
  attribute :email
end

What will be the JSON output keys for a user with id=1, name='Alice', email='alice@example.com'?
medium
A. {"id":1,"name":"Alice"}
B. {"id":1,"name":"Alice","email":"alice@example.com"}
C. {"id":1,"name":"Alice", "email":null}
D. NoMethodError due to 'attribute' usage

Solution

  1. Step 1: Check serializer attribute methods

    The serializer uses attributes (plural) and attribute (singular). Only attributes is valid; attribute is not a defined method and raises NoMethodError when the class is defined.
  2. Step 2: Determine output keys

    The serializer class fails to load due to the undefined method, preventing JSON output.
  3. Final Answer:

    NoMethodError due to 'attribute' usage -> Option D
  4. Quick Check:

    Undefined 'attribute' method causes error = D [OK]
Hint: Only use plural 'attributes' to include fields [OK]
Common Mistakes:
  • Using singular 'attribute' which causes NoMethodError
  • Expecting all fields to appear despite syntax error
  • Confusing attribute method names
4. Identify the error in this serializer code:
class PostSerializer < ActiveModel::Serializer
  attributes :id, :title

  def title
    object.title.upcase
  end

  def author_name
    object.author.name
  end
end
medium
A. Missing :author_name in attributes list, so it won't appear in JSON
B. Method 'title' should not be defined in serializer
C. Using 'object' is invalid inside serializer methods
D. Attributes list should include :author instead of :author_name

Solution

  1. Step 1: Check attributes declaration

    Only :id and :title are declared in attributes, so only these keys appear in JSON.
  2. Step 2: Check custom method usage

    Method author_name exists but is not listed in attributes, so it won't be serialized.
  3. Final Answer:

    Missing :author_name in attributes list, so it won't appear in JSON -> Option A
  4. Quick Check:

    Only declared attributes appear in JSON = B [OK]
Hint: Add custom methods to attributes list to include them [OK]
Common Mistakes:
  • Defining methods but forgetting to list them in attributes
  • Thinking all methods auto-serialize
  • Misusing 'object' inside serializer methods
5. You want to include a nested association in your JSON output using Active Model Serializers. Given these models:
class Article < ApplicationRecord
  belongs_to :author
end

class Author < ApplicationRecord
  has_many :articles
end

And these serializers:
class ArticleSerializer < ActiveModel::Serializer
  attributes :id, :title
  belongs_to :author
end

class AuthorSerializer < ActiveModel::Serializer
  attributes :id, :name
end

What will the JSON output for an article include regarding the author?
hard
A. The author will not be included unless manually added in controller
B. Only the author's id will be included as a number
C. The author will be included as a nested JSON object with :id and :name
D. The JSON will raise an error due to missing author attributes

Solution

  1. Step 1: Understand belongs_to in serializer

    Using belongs_to :author in ArticleSerializer includes the author association serialized by AuthorSerializer.
  2. Step 2: Check AuthorSerializer attributes

    AuthorSerializer defines :id and :name, so these fields appear nested inside article JSON.
  3. Final Answer:

    The author will be included as a nested JSON object with :id and :name -> Option C
  4. Quick Check:

    belongs_to includes nested object = C [OK]
Hint: Use belongs_to with serializer to nest associated objects [OK]
Common Mistakes:
  • Expecting only author id without serializer
  • Thinking associations need manual controller inclusion
  • Assuming missing attributes cause errors
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard