12

我有这个模板:

# app/views/posts/index.rabl
collection @posts => :posts
attributes :id, :title, :subject
child(:user) { attributes :full_name }
node(:read) { |post| post.read_by?(@user) }

女巫归来:

{
    "posts": [
        {
            "post": {
                "id": 5,
                "title": "...",
                "subject": "...",
                "user": {
                    "full_name": "..."
                },
                "read": true
            }
        }
    ]
}

我想添加一些分页参数以呈现:

{
    "posts": [
        {
            "post": {
                "id": 5,
                "title": "...",
                "subject": "...",
                "user": {
                    "full_name": "..."
                },
                "read": true
            }
        }
    ],
    "total": 42,
    "total_pages": 12
}

有任何想法吗?非常感谢!

4

4 回答 4

16

对不起,我的菜鸟问题,自述文件回答了 whitch。下面是一个分页示例:

object false

node(:total) {|m| @posts.total_count }
node(:total_pages) {|m| @posts.num_pages }

child(@posts) do
  extends "api/v1/posts/show"
end

注意:我Kaminari用于分页。

于 2012-02-17T10:06:02.690 回答
3

搜索时kaminarirabl这是第一个也是几乎唯一相关的结果。因此,我想在这里留下一个根据HAL 规范生成这样的链接解决方案。

所以首先,从视图开始:

# api/v1/posts/index.rabl
object false

child(@posts) do
  extends 'api/v1/posts/show'
end

node(:_links) do
  paginate @posts
end

然后继续定义分页方法:

# app/helpers/api_helper
module ApiHelper
  def paginate(collection)
    current_page_num = collection.current_page
    last_page_num = collection.total_pages

    {
      :first => first_page,
      :previous => previous_page(current_page_num),
      :self => current_page(current_page_num),
      :next => next_page(current_page_num, last_page_num),
      :last => last_page(last_page_num)
    }
  end

  def first_page
    { :href => url_for(:page => 1) }
  end

  def previous_page(current_page_num)
    return nil if current_page_num <= 1
    { :href => url_for(:page => current_page_num-1) }
  end

  def current_page(current_page_num)
    { :href => url_for(:page => current_page_num) }
  end

  def next_page(current_page_num, last_page_num)
    return nil if current_page_num >= last_page_num
    { :href => url_for(:page => current_page_num+1) }
  end

  def last_page(last_page_num)
    { :href => url_for(:page => last_page_num) }
  end
end

最后,将助手包含在必要的控制器中。助手可以包含在 aApi::BaseController中,所有 API 控制器都从中继承:

helper :api

如果没有 Zag zag 的解决方案,我无法做到这一点,所以.. 非常感谢!

于 2013-05-09T11:59:39.600 回答
1

请注意,对于 will_paginate 3.0.0,以下工作:

node(:total) {|m| @posts.total_entries }
node(:total_pages) {|m| (@posts.total_entries.to_f / @posts.per_page).ceil }
node(:page_num){|m| @posts.current_page}
于 2012-08-21T12:15:58.630 回答
0

这可能是您正在寻找的;)

object false
node :comments do
  partial('posts/index', object: @posts)
end

node(:pagination) do
  {
    total:@posts.count,
    total_pages: 20
  }
end
于 2013-06-20T20:01:18.950 回答