rails API活动模型序列化程序根节点无法正常工作

时间:2016-08-06 12:11:31

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

我有一个rails 4.2.5 api应用程序。由于某种原因,json根节点不包含在响应中,我不明白为什么。

curl  http://localhost:3000/api/v1/category/science

返回

{"title":"science","sub_categories":34}%

而不是

{"category": {"title":"science","sub_categories":34}%}

代码:

控制器

class Api::V1::CategoryController < ApplicationController
  def show
    category = params[:category] || "sports"
    @category = Category.where(cat_title: category.capitalize).first
    respond_to do |format|
      format.json { render json: @category, serializer: CategorySerializer, root: "category" }
    end
  end
end

串行

class CategorySerializer < ActiveModel::Serializer
  attributes :title, :sub_categories

  def title
    URI::encode(object.cat_title.force_encoding("ISO-8859-1").encode("utf-8", replace: nil).downcase.tr(" ", "_"))
  end

  def sub_categories
    object.cat_subcats
  end
end

2 个答案:

答案 0 :(得分:3)

查看初始值设定项,这应该在wrap_paramters.rb中注释掉:

# To enable root element in JSON for ActiveRecord objects.
# ActiveSupport.on_load(:active_record) do
#   self.include_root_in_json = true
# end

答案 1 :(得分:1)

Rails 5.0.0.1 使用ActiveMovelSerializers(0.10.2),您只需添加初始化程序:

应用程序/配置/初始化/ json_api.rb

require 'active_model_serializers/register_jsonapi_renderer'

ActiveModelSerializers.config.adapter = :json_api