grape-jsonapi icon indicating copy to clipboard operation
grape-jsonapi copied to clipboard

Have to pass to_a for ActiveRecord_Relation if result is empty

Open code-bunny opened this issue 1 year ago • 0 comments

Greetings,

There is a wee bit of a issue where if you have a empty response from ActiveRecord and don't specifically call to_a then it'll return something like {"data":"#<Bundle::ActiveRecord_Relation:0x00000001189bfd20>"} instead of {"data":[]} as we would expect and this is the correct result if we call to_a after running our query.

Now the question is then raised on what is the correct solution.

Should we always call to_a after making a query? Should the gem be 'fixed' to handle an empty ActiveRecord_Relation?

Below is a sample Grape API mounted on Rails 8.0.1 with Ruby 3.4.1

module Bundles
  class API < Grape::API
    version "v1", using: :header, vendor: "codebunnies"
    prefix :api

    content_type :jsonapi, "application/vnd.api+json"
    formatter :json, Grape::Formatter::Jsonapi
    formatter :jsonapi, Grape::Formatter::Jsonapi
    format :jsonapi

    resources :bundles do
      get do
        render Bundle.all
      end

      get "bad_response" do
        render Bundle.where(title: "Surely doesn't exist")
      end

      get "good_response" do
        render Bundle.where(title: "Surely doesn't exist").to_a
      end
    end
  end
end

code-bunny avatar Jan 19 '25 17:01 code-bunny