will_paginate JSON支持?

时间:2011-01-15 10:54:38

标签: ruby-on-rails ruby json gem will-paginate

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

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

7 个答案:

答案 0 :(得分:40)

以下内容:

@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

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

答案 1 :(得分: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

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

  

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

响应头看起来像这样

> 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

Source -Adding Pagination to an API

答案 2 :(得分:2)

最简单的解决方案

  def index
    @posts =  Post.all.paginate(:page => params[:page], :per_page => 4)
    render :json => @posts.to_json(:methods => [:image_url])
  end

您只需添加gem 'will_paginate'

即可

它对我有用。

答案 3 :(得分:2)

这个帮助我:

将此方法添加到基本API控制器。

def pagination_dict(collection)
  {
    current_page: collection.current_page,
    next_page: collection.next_page,
    prev_page: collection.prev_page, # use collection.previous_page when using will_paginate
    total_pages: collection.total_pages,
    total_count: collection.total_count # use collection.total_entries when using will_paginate
  }
end

然后,在渲染方法上使用它。

render json: posts, meta: pagination_dict(posts)

答案 4 :(得分:1)

will_paginate只是以切片方式取回记录。所以它只是从你的数据库中获取一个数组。

当你渲染为json时,那些rails遍历对象数组并在它们上面调用as_json。

所以是的,你可以将渲染为json。

答案 5 :(得分:1)

我建议您观看此Railscast:Pagination with AJAX

答案 6 :(得分:0)

Gem:will_paginate,版本 3.1.8

  def pagination_meta(collection)
    {
      current_page: collection.current_page,
      next_page: collection.next_page,
      prev_page: collection.previous_page,
      total_page: collection.total_pages,
      total_count: collection.total_entries,
    } if collection.present?
  end