使用active_model_serializer gem和Rails API以及will_paginate / kaminari时如何发送206状态代码

问题描述 投票:0回答:2

我正在使用带有will_paginate gem的AMS,Rails 5.2.2 API。它可以根据需要工作,但响应代码是200而不是206

#adsresses_controller

def index
  @addresses = Address.all.paginate(page: params[:page], per_page: 25)
  json_response(@addresses, :ok, include: ['shop', 'shop.country'])
end

其中json_response只是controllers/concerns/response.rb中定义的方法:

module Response
  extend ActiveSupport::Concern

  def json_response(object, status = :ok, opts = {})
    response = {json: object, status: status}.merge(opts)
    render response
  end
...
end

问题是发送正确响应的最佳规则是什么, - 如果是分页响应,则为200或206?

谢谢。

active-model-serializers rails-api
2个回答
0
投票

https://guides.rubyonrails.org/layouts_and_rendering.html

2.2.12.4:status选项Rails将自动生成具有正确HTTP状态代码的响应(在大多数情况下,这是200 OK)。您可以使用:status选项更改此设置:

render status: 500
render status: :forbidden

您的回复代码是

200

因为你用:ok要求它。

你应该用以下方法解决这个问题:

json_response(@addresses, 206, include: ['shop', 'shop.country'])

要么

json_response(@addresses, :partial_content, include: ['shop', 'shop.country'])

https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/206

HTTP 206部分内容成功状态响应代码指示请求已成功并且正文包含所请求的数据范围,如请求的Range标头中所述。

因此,我认为主要取决于您的应用程序。


0
投票

我遇到的解决方案是向controllers/concerns/response.rb添加一个帮助方法,以便能够为分页响应返回正确的状态:

def paginated_response_status(collection)
  collection.size > WillPaginate.per_page ? :partial_content : :ok
end

并在需要时在AdressesController动作中使用它:

#controllers/api/addresses_controller.rb

def index
  @addresses = Address.all
  paginate(
    json: @addresses, 
      include: ['shop', 'shop.country'],
      status: paginated_response_status(@addresses) 
  )
end

上面的例子是will_paginate gem和api-pagination gem。

希望这可以帮助。

© www.soinside.com 2019 - 2024. All rights reserved.