0
0
Ruby on Railsframework~10 mins

Serializers (Active Model Serializers) in Ruby on Rails - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to define a serializer class for a User model.

Ruby on Rails
class UserSerializer < ActiveModel::Serializer
  attributes [1]
end
Drag options to blanks, or click blank then click option'
A:id, :name, :email
Bid, name, email
C[:id, :name, :email]
D'id', 'name', 'email'
Attempts:
3 left
💡 Hint
Common Mistakes
Using strings instead of symbols for attribute names.
Passing an array instead of a list of symbols.
2fill in blank
medium

Complete the code to add a custom method attribute to the serializer.

Ruby on Rails
class UserSerializer < ActiveModel::Serializer
  attributes :id, :name, :email, [1]

  def [1]
    object.name.upcase
  end
end
Drag options to blanks, or click blank then click option'
Aupcase_name
Buppercase_name
Cname_upper
Dname_caps
Attempts:
3 left
💡 Hint
Common Mistakes
Mismatch between attribute name and method name.
Using invalid Ruby method names.
3fill in blank
hard

Fix the error in the serializer to correctly include an association.

Ruby on Rails
class UserSerializer < ActiveModel::Serializer
  attributes :id, :name
  has_many [1]
end
Drag options to blanks, or click blank then click option'
A:posts
Bposts
Cpost
D:post
Attempts:
3 left
💡 Hint
Common Mistakes
Omitting the colon before the association name.
Using singular form for a has_many association.
4fill in blank
hard

Fill both blanks to define a belongs_to association with a custom serializer.

Ruby on Rails
class CommentSerializer < ActiveModel::Serializer
  attributes :id, :content
  belongs_to [1], serializer: [2]
end
Drag options to blanks, or click blank then click option'
A:user
BUserSerializer
C:post
DPostSerializer
Attempts:
3 left
💡 Hint
Common Mistakes
Using string instead of symbol for association name.
Passing serializer name as a string instead of a constant.
5fill in blank
hard

Fill in the blanks to create a serializer with conditional attributes and a custom method.

Ruby on Rails
class ProductSerializer < ActiveModel::Serializer
  attributes :id, :name, [1]

  attribute :discounted_price, if: -> { [2] }

  def discounted_price
    object.price * 0.9
  end
end
Drag options to blanks, or click blank then click option'
A:price
Bobject.on_sale?
Cobject.in_stock?
D:stock
Attempts:
3 left
💡 Hint
Common Mistakes
Using incorrect attribute names.
Wrong condition lambda syntax.