DEV Community

bc-kelly
bc-kelly

Posted on

Conditional Rails Serializers

Over the last few weeks while learning Ruby on Rails, one of my most common searches was serializer. The issue I came across most frequently was trying to use serializer on only one action in a model, while not using it on the other.

Here is an example to show the issue I came across and how I solved it. The model I was working on was Episodes, and the two actions I was working on were show and index. I was looking to display all of my episodes along with their attributes with the index action. And I was looking to display only one episode with the show action, but also with the nested Guest information associated with that episode. When I tried to utilize a serializer in the show action, it affected my index action as well.

In order to get around this, I used a flag in my serializer. Using a flag in the serializer with a condition allows you to restrict the serializer from applying to the action where you do not want it to apply. Below is the code in my serializer and my controller.

class EpisodeSerializer < ActiveModel::Serializer
  attributes :id, :date, :number

  has_many :guests, if: :condition

  def condition
    @instance_options[:flag] != "restrict"
  end

end
Enter fullscreen mode Exit fullscreen mode
class EpisodesController < ApplicationController

    def index 
        @episode = Episode.all
        render json: @episode, flag: "restrict", status: :ok
    end


    def show 
        episode = Episode.find(params[:id])
        render json: episode, serializers: EpisodeSerializer, status: :ok
    end
end
Enter fullscreen mode Exit fullscreen mode

Below is the response for the index action, showing only the episode data:

[
    {
        "id": 1,
        "date": "1/11/99",
        "number": 1
    },
    {
        "id": 2,
        "date": "1/12/99",
        "number": 2
    },
......
Enter fullscreen mode Exit fullscreen mode

Below is the response for the show action for one episode with the nested guest data as a result of the episode serializer:

{
    "id": 1,
    "date": "1/11/99",
    "number": 1,
    "guests": [
        {
            "id": 1,
            "name": "Michael J. Fox",
            "occupation": "actor"
        }
    ]
}
Enter fullscreen mode Exit fullscreen mode

This is my first blog post and I am new to Rails so if there are any suggestions, please feel free to leave a comment below!

Top comments (0)