【问题标题】:Rails-API getting AbstractController::DoubleRenderError in API::V1::Controller#indexRails-API 在 API::V1::Controller#index 中获取 AbstractController::DoubleRenderError
【发布时间】:2016-05-03 17:49:32
【问题描述】:

嘿,我正在开发一个简单的 API,它从数据库中获取信息并将其作为 JSON 对象返回,并且它不会正常工作。我不断得到:

API::V1::BusinessesController#index 中的AbstractController::DoubleRenderError 在此操作中多次调用渲染和/或重定向。请注意,您只能调用渲染或重定向,并且每个操作最多调用一次。还要注意,redirect和render都不会终止action的执行,所以如果你想在redirect后退出一个action,你需要做一些类似“redirect_to(...) and return”的操作。

class API::V1::BusinessesController < ApplicationController
  # GET /businesses
  def index
    @businesses = Business.all

    render json: @businesses, status: :ok
    paginate json: @businesses, per_page: 50
  end

  # GET /business/#
  def show
    @business = Business.find(params[:id])

    render json: @business, status: :ok
  end
end

另外,当我$curl -H "Content-Type: application/json" http://localhost:3000/api/v1/businesses/1 时,我只返回{"business":{"id":1}},而不是应该是{"business":{id:1, name:costco, etc}} 的整个json 对象

如果需要更多信息,请告诉我,完整的 repo 位于 github.com/dmonaco05/business-api 谢谢。

【问题讨论】:

    标签: ruby-on-rails json api


    【解决方案1】:

    第一个问题是因为您的控制器中有renderpaginate。选择一个。

    def index
      @businesses = Business.all
      paginate json: @businesses, per_page: 50
    end
    

    第二个问题与您的序列化程序有关。将所有必填字段添加到您的 UserSerializer 或删除该类以使其正常运行。

    class BusinessSerializer < ActiveModel::Serializer
      attributes :id, :name, etc.
    end
    

    【讨论】:

    • 非常感谢!当我看到这个响应时,我刚刚弄清楚了序列化程序部分。
    猜你喜欢
    • 2014-07-02
    • 1970-01-01
    • 1970-01-01
    • 2016-01-28
    • 2015-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多