Comment paginer les collections de Rabl
-
26-10-2019 - |
Question
J'ai ce modèle:
# app/views/posts/index.rabl
collection @posts => :posts
attributes :id, :title, :subject
child(:user) { attributes :full_name }
node(:read) { |post| post.read_by?(@user) }
retourne Sorcières:
{
"posts": [
{
"post": {
"id": 5,
"title": "...",
"subject": "...",
"user": {
"full_name": "..."
},
"read": true
}
}
]
}
Et je voudrais ajouter ajouter quelques params afin de paginations rendre ceci:
{
"posts": [
{
"post": {
"id": 5,
"title": "...",
"subject": "...",
"user": {
"full_name": "..."
},
"read": true
}
}
],
"total": 42,
"total_pages": 12
}
Toutes les idées? Un grand merci!
La solution
Désolé pour ma question noob, whitch a été répondu par le README. Voici un exemple de Pagination:
object false
node(:total) {|m| @posts.total_count }
node(:total_pages) {|m| @posts.num_pages }
child(@posts) do
extends "api/v1/posts/show"
end
Note:. J'utilise Kaminari
pour la pagination
Autres conseils
Lors de la recherche de kaminari
et rabl
c'est la première et à peu près seul résultat pertinent. En tant que tel, je voudrais laisser ici une solution selon la HAL Spécification qui génère des liens comme cette .
Alors d'abord, commencer par la vue:
# api/v1/posts/index.rabl
object false
child(@posts) do
extends 'api/v1/posts/show'
end
node(:_links) do
paginate @posts
end
Passez ensuite à définir la méthode 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
Et enfin, inclure l'aide dans les contrôleurs nécessaires. L'aide pourrait être inclus dans un Api::BaseController
, à partir de laquelle tous les contrôleurs API hériteront:
helper :api
Je ne pouvais pas faire cela sans Zag zag .. solution d ', donc .. Merci beaucoup!
note pour will_paginate 3.0.0 Les travaux suivants:
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}
Cela pourrait être ce que vous cherchez;)
object false
node :comments do
partial('posts/index', object: @posts)
end
node(:pagination) do
{
total:@posts.count,
total_pages: 20
}
end