skip to Main Content

I’m using the rails gem shopify API gem to fetch shopify products. I’m fetching products like this:

ShopifyAPI::Product.find(:all, params: { page: parmas[:page], 
                                          limit: 10, 
                                          title: params[:search]
                                        })

this API returns products searched by title with limit 10.
So How can I add pagination on my view or can I use will_paginate gem for it?
Please help!, thanks! in advance.

2

Answers


  1. You can use Kaminari.paginate_array(*args) with array(array of Shopify products) as first argument and with option as hash, where you have to set value to total_count key.

    Full example:

    @paginatable_array = Kaminari.paginate_array(@shopify_products, total_count:145).page(1).per(10)
    

    use 1 as argument to .page method, because your array will contain only 10 objects(if limit is 10 and 10 objects in view)
    In view just use helper method

    <%= paginate @paginatable_array %>
    

    I hope that it will help!

    Login or Signup to reply.
  2. I think is late for your work. But this how to it:

    Example

    @orders = ShopifyAPI::Order.find(:all, :params => {:status => "any", :limit => 3, :order => "created_at DESC" })
    @orders.each do |order|
    
      id = order.id
      name = order.name
    end
    
    while @orders.next_page?
      @orders = @orders.fetch_next_page
      @orders.each do |order|
    
        id = order.id
        name = order.name
      end
    end
    

    So you can create paginable array based on what you receive in each loop. The first call defines the limit for all subsequents call to fetch_next_page. In my case each page contain 3 element, you can go up to 250.

    Another way is to navigate using shopify "next_page_info" parameter, so you only need to fetch the first query and include all filters, then just navigate back/fwd with page infos(previous_page_info or next_page_info).

    Example 2
    first_batch_products = ShopifyAPI::Product.find(:all, params: { limit: 50 })
      second_batch_products = ShopifyAPI::Product.find(:all, params: { limit: 50, page_info: first_batch_products.next_page_info })
    
    next_page_info = @orders.next_page_info
    prev_page_info = @orders.previous_page_info
    

    More info here: https://github.com/Shopify/shopify_api#pagination

    Regards.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search