Skip to content

Instantly share code, notes, and snippets.

@benkoshy
Last active January 31, 2024 02:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save benkoshy/49e5e61c8ab9acfdb587e8e9f277864a to your computer and use it in GitHub Desktop.
Save benkoshy/49e5e61c8ab9acfdb587e8e9f277864a to your computer and use it in GitHub Desktop.
Pagy jsonapi considerations

The Old Way

class QuotesController < ApplicationController  

  def index   
    # assuming jsonapi extra is enabled
    @pagy, @quotes = pagy(Quote.all) 

    # this will fail if we are using a html pagy_nav helper
    # because the urls generated from that helper will not be nested
    
    
    # recent PR will either nest them all, or not nest them depending on the default.

    respond_to do |format|      
      format.html  
      format.json 
    end
  end
end

Workflow To Consider:

Both links hit the same controller:

"https://example.com/products?page[number]=1&page[size]=50&....json" # ends with .json
"https://example.com/products?page=1&page=50" # not nested

...and then the everything just works:

class QuotesController < ApplicationController
  include Pagy::Backend  

  def index      

    respond_to do |format|      
      
      format.html  do 
        @pagy, @quotes = pagy(Quote.all)                # deliver non-nested params
      end

      format.json do 
        @pagy, @quotes = pagy(Quote.all, jsonapi: true) # helpers deliver nested param urls
      end
    end
  end
end

Pros and Cons:

  • Links must end with .json.
  • If users don't want the .json extension on the links then they must select the correct default - and json vs html end points perhaps cannot be mixed: they must then be separated - unless there is a way of detecting whether they are nested or not (which is another possibility, but not one that I like)?
  • Users can set the default to whatever they like and make the decisions accordingly.
  • The queries are within the html/json render blocks. Not pretty, but perhaps manageable?

My two cents.

@ddnexus
Copy link

ddnexus commented Jan 18, 2024

You need also to set the DEFAULT[:jsonapi] = false in the initializer, so it will work on demand as your code imply.
As an alternative you leave the default to true, but you should disable it in all the regular requests.

@ddnexus
Copy link

ddnexus commented Jan 18, 2024

BTW, you may even keep the params nesting in all the app. It will all work without setting the jsonapi ever.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment