Cómo paginar las colecciones de Rabl
-
26-10-2019 - |
Pregunta
Tengo esta plantilla:
# app/views/posts/index.rabl
collection @posts => :posts
attributes :id, :title, :subject
child(:user) { attributes :full_name }
node(:read) { |post| post.read_by?(@user) }
Witch regresa:
{
"posts": [
{
"post": {
"id": 5,
"title": "...",
"subject": "...",
"user": {
"full_name": "..."
},
"read": true
}
}
]
}
Y me gustaría agregar para agregar algunos parámetros de paginación para representar esto:
{
"posts": [
{
"post": {
"id": 5,
"title": "...",
"subject": "...",
"user": {
"full_name": "..."
},
"read": true
}
}
],
"total": 42,
"total_pages": 12
}
¿Algunas ideas? ¡Muchas gracias!
Solución
Perdón por mi pregunta de novato, Whitch fue respondido por el readme. Aquí hay un ejemplo de paginación:
object false
node(:total) {|m| @posts.total_count }
node(:total_pages) {|m| @posts.num_pages }
child(@posts) do
extends "api/v1/posts/show"
end
Nota: Estoy usando Kaminari
para la paginación.
Otros consejos
Al buscar kaminari
y rabl
Este es el primer y solo resultado relevante. Como tal, me gustaría dejar aquí una solución según el Especificación HAL que genera enlaces como este.
Así que primero, comience con la vista:
# api/v1/posts/index.rabl
object false
child(@posts) do
extends 'api/v1/posts/show'
end
node(:_links) do
paginate @posts
end
Luego proceda a definir el método paginado:
# 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
Y finalmente, incluya el ayudante en los controladores necesarios. El ayudante podría ser incluido en un Api::BaseController
, de la cual todos los controladores API heredan:
helper :api
No podría haber hecho esto sin la solución de Zag Zag, así que ... ¡muchas gracias!
Nota, para will_paginate 3.0.0 Los siguientes funcionan:
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}
Esto podría ser lo que estás buscando;)
object false
node :comments do
partial('posts/index', object: @posts)
end
node(:pagination) do
{
total:@posts.count,
total_pages: 20
}
end