Search code examples
ruby-on-railsactive-model-serializersruby-on-rails-5

Rails active_model_serializer conditional include


When I have a has_many/belongs_to relationship in Rails 5 API with active_model_serializers I can pass the option to include a nested model.

def show
    render json: @post, include: ['comments']
end

It's also possible to get multiple layers of nesting.

def show
    render json: @post, include: ['comments', 'comments.comment_likes']
end

I can't find documentation anywhere about adding conditions to the include statement. Is it possible to do something like this?

def show
    render json: @post, include: ['comments'] { top_contributor: true } 
end

Solution

  • In master (which will soon become RC4), a PR has been merged that allows for the following at serializer level:

    belongs_to :user, if: :include_user?
    def include_user?
      current_user.admin?
    end