Search code examples
ruby-on-railsactive-model-serializers

serializer is not beeing used if included in a hash


ActiveModelSerializers.config.default_includes = '**'

we render the comments via a serializer, including the author and some infos.

this is using the serializer and everything works great

render json: comments

however, we also need to send additional meta-data, so we wrap it into a hash. unfortunately this is not using the serializer and we can't figure out why

render json: {comments: comments, upvoted: upvoted, downvoted: downvoted}

Solution

  • according to the git

    https://github.com/rails-api/active_model_serializers/issues/2102#issuecomment-293292697

    it is not possible to automatically use a serializer if we render a hash, rather then a collection. the workaround is

    json = Hash.new
    json[:comments] = ActiveModel::SerializableResource.new(comments)
    json[:upvoted] = upvoted
    json[:downvoted] = downvoted
    render status: :ok, json: json