【问题标题】:Unusual Response for simple json render with active model serializer使用活动模型序列化程序的简单 json 渲染的异常响应
【发布时间】:2014-12-07 04:43:21
【问题描述】:

我的 Rails 4 项目中有以下文件:

lists_controller.rb

class Api::V1::ListsController < Api::V1::ApiController
  before_action :set_list, only: [:show]

  attr_accessor :list

  def show
    respond_with list
  end

  private

  def set_list
    @list = List.where(id: params[:id]).first
    render_list_not_found if @list.nil?
  end

  def render_list_not_found
    render json: { "list" => { message: "List not found" } }, status: 404
  end

end

list_serializer.rb

class ListSerializer < ActiveModel::Serializer
  embed :ids, include: true

  attributes :id, :title, :start_date, :end_date

  has_many :items
end

当我使用已存在列表的 id 访问 API 时,我会返回正确的 json。但是当你传递一个无效的 id 时,你会认为你会得到这个:

 {
  "list": {
     "message": "List not found"
   }
 }

而是得到这个:

 {
    "lists": [
        [
            "list",
            [
                [
                    "message",
                    "List not found."
                ]
            ]
        ]
    ]
}

知道为什么会这样吗?

【问题讨论】:

    标签: ruby-on-rails json ruby-on-rails-4 active-model-serializers


    【解决方案1】:

    即使使用简单的渲染,似乎也正在调用活动模型序列化程序。我使用的是 gem 的 0.9.1 版本,但降级到 0.9.0 似乎可以解决问题。很奇怪。

    【讨论】:

      猜你喜欢
      • 2018-02-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多