will_paginate JSON支持?

16 ruby gem json ruby-on-rails will-paginate

我想知道是否有人可以告诉我,如果will_paginate可以支持开箱即用的JSON,或者是否必须被黑客入侵?

我想将页面数据添加到JSON响应中,而will_paginate管理分页.

mis*_*lav 41

有些东西:

@posts = Post.paginate :page => params[:page]

respond_to do |format|
  format.json {
    render :json => {
      :current_page => @posts.current_page,
      :per_page => @posts.per_page,
      :total_entries => @posts.total_entries,
      :entries => @posts
    }
  }
end
Run Code Online (Sandbox Code Playgroud)

一旦确定了所需的格式,就可以to_json在WillPaginate :: Collection上定义一个方法.

  • 查看GitHub API文档[1],以便更好地在响应中编码分页(提示:将其放在标题中)[1]:http://developer.github.com/v3/#pagination (3认同)
  • 你是怎么找到这些方法的?它们未列在will_paginate wiki中. (2认同)

Kal*_*lah 8

将分页添加到API

我用will_pagination找到了一个简单的API Json Response Pagination解决方案.

首先创建一个类方法,ApplicationController然后创建一个after_filter将在响应头中设置分页元数据:

application_controller.rb

class ApplicationController < ActionController::Base

  protected
  def self.set_pagination_headers(name, options = {})
    after_filter(options) do |controller|
      results = instance_variable_get("@#{name}")
      headers["X-Pagination"] = {
        total: results.total_entries,
        total_pages: results.total_pages,
        first_page: results.current_page == 1,
        last_page: results.next_page.blank?,
        previous_page: results.previous_page,
        next_page: results.next_page,
        out_of_bounds: results.out_of_bounds?,
        offset: results.offset
      }.to_json
    end
  end

end
Run Code Online (Sandbox Code Playgroud)

然后在控制器中我们想要添加分页标题,我们可以像这样调用它:

widgets_controller.rb

class Api::V1::WidgetsController < Api::V1::BaseController
  set_pagination_headers :widgets, only: [:index]

  def index
    @widgets = Widget.all.paginate(params).order("created_at desc")
    respond_with @widgets
  end

end
Run Code Online (Sandbox Code Playgroud)

响应标头看起来像这样

> Cache-Control:max-age=0, private, must-revalidate
> Connection:keep-alive Content-Type:application/json; charset=utf-8
> Etag:"fe70f7bae4c6e5cdea7867aa7fc0c7b4"
> X-Pagination:{"total":14,"total_pages":1,"first_page":true,"last_page":true,"previous_page":null,"next_page":null,"out_of_bounds":false,"offset":0}
> Server:thin 1.3.1 codename Triple Espresso
> Set-Cookie:_widgets_session=BAh7CEkiD3Nlc3Npb25faWQGOgZFRkkiJTAzYjVlNzkwZTIyNzU4YTYwMDU0M2MwOTQ2ZWI3YWU2BjsAVEkiDWxhc3RfdXJsBjsARkkiM2h0dHA6Ly9tYWluYW5kbWUtc3RhZ2luZy5oZXJva3VhcHAuY29tL3VzZXJzLzEGOwBGSSIQX2NzcmZfdG9rZW4GOwBGSSIxdjd0SEp6cVhKamh5YTh1cnBUdmpBb0w5aVA0bS9QTEdON3g1UlFUYnBkND0GOwBG--71b3a24c216a414d8db04f312b5300c818e6bba4;
> path=/; HttpOnly Transfer-Encoding:Identity
> X-Request-Id:61b383ade49cba8b24a715a453ed6e1f X-Runtime:0.191485
> X-Ua-Compatible:IE=Edge,chrome=1
Run Code Online (Sandbox Code Playgroud)

源 - 将分页添加到API