Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Have to pass to_a for ActiveRecord_Relation if result is empty #49

Open
code-bunny opened this issue Jan 19, 2025 · 0 comments
Open

Have to pass to_a for ActiveRecord_Relation if result is empty #49

code-bunny opened this issue Jan 19, 2025 · 0 comments

Comments

@code-bunny
Copy link

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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant