title: Rails pagination in API using Her, Faraday
body: <p>I've been trying to figure this out all day, and it's driving me crazy.</p>
  
  <p>I have two rails apps, ServerApp and ClientApp. ClientApp gets data from ServerApp through an API, using the Her gem. Everything was great until I needed pagination information.</p>
  
  <p>This is the method I am using to get the orders (this uses kamainari for pagination and ransack for search):</p>
  
  <pre class="lang-rb prettyprint-override"><code># ServerApp
  def search
    @search = Order.includes(:documents, :client).order('id desc').search(params[:q])
    @orders = @search.result(distinct: true).page(params[:page]).per(params[:per])
  
    respond_with @orders.as_json(include: :documents)
  end
  </code></pre>
  
  <p>It returns an array of hashes in json, which Her uses as a collection of orders. That works fine.</p>
  
  <pre class="lang-rb prettyprint-override"><code># Response
  [
    {
      "client_id": 239,
      "created_at": "2013-05-15T15:37:03-07:00",
      "id": 2422,
      "ordered_at": "2013-05-15T15:37:03-07:00",
      "origin": "online",
      "updated_at": "2013-05-15T15:37:03-07:00",
      "documents": [
        { ... }
      ]
    },
    ...
  ]
  </code></pre>
  
  <p>But I needed pagination information. It looked like I needed to <a href="https://github.com/remiprev/her/issues/82" rel="noreferrer">send it as metadata with my json</a>. So I change my response to this:</p>
  
  <pre class="lang-rb prettyprint-override"><code>respond_to do |format|
    format.json do
      render json: { orders: @orders.as_json(include: :documents), metadata: 'sent' }
    end
  end
  </code></pre>
  
  <p>This does indeed send over metadata, so in my ClientApp I can write @orders.metadata and get 'sent'. But now my orders are nested in an array inside of 'orders', so I need to use  @orders.orders, and then it treats it like an array instead of a Her collection.</p>
  
  <p>After doing some reading, it seemed sending pagination info through headers was the way a lot of other people did this (I was able to get the headers set up in an after_filter using <a href="http://metabates.com/2012/02/22/adding-pagination-to-an-api/" rel="noreferrer">this guide</a>). But I am even more lost on how to get those response headers in my ClientApp - I believe I need a Faraday Middleware but I just am having no luck getting this to work.</p>
  
  <p>If anyone knows how I can just get this done, I would be very grateful. I can't take another day of banging my head against the wall on this, but I feel like I am just <em>one vital piece of info away</em> from solving this!</p>