2016-08-06 11 views
0

私はレール4.2.5 APIアプリケーションを持っています。何らかの理由で、jsonルートノードが応答に含まれていないため、なぜ私は理解できません。rails APIアクティブモデルシリアライザルートノードが動作しない

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 

答えて

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 
+0

私もこの 'ActiveModelSerializers.config.adapter =:json'を追加しなければならなかった –

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 
+0

ありがとう、私はすでにそれを考え出した。 –

+0

Rails 4.2.5の回答を追加した方が便利です。 将来の参照のためにRails 5.0.0.1用に追加したので、mineを答えとしてマークしないでください。たぶん、あなたがやったことを追加するか、またはphoetの答えが正しい場合は、彼を答えとしてマークしてください。 – rmcsharry

関連する問題