我使用 active_model_serializers gem,并且需要获取 Service 模型的嵌套属性
class Category < ActiveRecord::Base
has_many :subcategories
end
class Subcategory < ActiveRecord::Base
has_many :services
end
class Service < ActiveRecord::Base
belongs_to :subcategory
end
序列化器:
class CategorySerializer < ActiveModel::Serializer
attributes :id, :title
has_many :subcategories, serializer: SubcategorySerializer
end
class SubcategorySerializer < ActiveModel::Serializer
attributes :id, :title
has_many :services, serializer: SubcategorySerializer
end
class ServiceSerializer < ActiveModel::Serializer
attributes :id, :title
end
类别控制器:
class CategoriesController < BaseController
def index
categories = Category.all
render json: categories, each_serializer: CategorySerializer
end
end
类别序列化程序不返回 Service 模型的嵌套属性。
{
"id": 1,
"title": "Category 1",
"subcategories": [
{
"id": 1,
"title": "Sub category 1"
},
{
"id": 2,
"title": "Sub category 2"
}
]
}
我需要在子类别中使用嵌套服务模型获取json结果 我正在使用 active_model_serializers(〜> 0.10.2) 怎么办?
答案 0 :(得分:2)
在config/initializers/active_model_serializer.rb
文件中添加ActiveModel::Serializer.config.default_includes = '**'