質問

私はこのテンプレートを持っています:

# 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
}

何か案は?どうもありがとう!

役に立ちましたか?

解決

私のnoobの質問で申し訳ありませんが、ウィッチはreadmeに答えられました。これがページネーションの例です:

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 ページネーションのため。

他のヒント

検索するとき kaminarirabl これは、最初で唯一の関連する結果です。そのため、私はここに解決策を残したいと思います HAL仕様 次のようなリンクが生成されます これ.

まず、ビューから始めてください。

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

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

node(:_links) do
  paginate @posts
end

次に、Paginateメソッドの定義に進みます。

# 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

そして最後に、必要なコントローラーにヘルパーを含めます。ヘルパーはaに含めることができます Api::BaseController, 、そこからすべてのAPIコントローラーが継承します。

helper :api

Zag Zag ..の解決策なしでこれを行うことはできなかったので、どうもありがとうございました!

注、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}

これはあなたが探しているものかもしれません;)

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

node(:pagination) do
  {
    total:@posts.count,
    total_pages: 20
  }
end
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top