在具有活动资源的API上实现分页的最佳方式是什么?我正在构建API和使用API的应用程序,所以我需要等式的两端。
我见过人们在ActiveResource中为他们想要的页面设置页眉(例如X-PERPAGE)。
任何建议都是很棒的。寻找最佳解决方案。
发布于 2012-01-10 00:10:23
1)用下一个代码修补activeresource
module ActiveResource
class Connection
alias_method :origin_handle_response, :handle_response
def handle_response(response)
Thread.current["active_resource_response_#{self.object_id}"] = response
origin_handle_response(response)
end
def response
Thread.current["active_resource_response_#{self.object_id}"]
end
end
end 它将增加在执行rest方法后读取响应的可能性2)在服务器端使用kaminari,您可以执行下一步操作
@users = User.page(params[:page]).per(params[:per_page])
response.headers["total"] = @users.total_count.to_s
response.headers["offset"] = @users.offset_value.to_s
response.headers["limit"] = @users.limit_value.to_s
respond_with(@users)3)再次在客户端使用kaminari
users = Users.all(:params=>params)
response = Users.connection.response
@users = Kaminari::PaginatableArray.new(
users,
{
:limit => response['limit'].to_i ,
:offset =>response['offset'].to_i ,
:total_count => response['total'].to_i
}
)发布于 2013-04-30 12:34:03
ActiveResource 4.0.0.beta1引入了ActiveResource::Collection,它(根据源代码中的文档)是一个处理解析索引响应的包装器。可以通过以下方式设置Post类来处理它:
class Post < ActiveResource::Base
self.site = "http://example.com"
self.collection_parser = PaginatedCollection
end您可以将分页数据嵌入到您的API响应中,并使用ActiveResource::Collection检索它们。
有关如何使用它的详细说明,请参阅:http://javiersaldana.com/2013/04/29/pagination-with-activeresource.html
https://stackoverflow.com/questions/8275223
复制相似问题