Ruby on rails 活动模型序列化程序,无数组根,但为子根
我已经将活动模型序列化器gem添加到一个项目中,它打破了一堆东西,我们的一个api有一个非常特殊的格式,我需要保留,不幸的是,我似乎无法获得遗留行为Ruby on rails 活动模型序列化程序,无数组根,但为子根,ruby-on-rails,active-model-serializers,Ruby On Rails,Active Model Serializers,我已经将活动模型序列化器gem添加到一个项目中,它打破了一堆东西,我们的一个api有一个非常特殊的格式,我需要保留,不幸的是,我似乎无法获得遗留行为 #Models class Parent < ActiveRecord::Base attr_accessable, :id, :name, :options has_many :children end class Child < ActiveRecord::Base attr_accessable, :id, :nam
#Models
class Parent < ActiveRecord::Base
attr_accessable, :id, :name, :options
has_many :children
end
class Child < ActiveRecord::Base
attr_accessable, :id, :name
end
#Controller
class ParentsController < ApplicationController
respond_to :json
def index
#Was
@parents = Parent.all
respond_with @parents, :include => [:children]
#Is (and is not working)
@parents = Parent.includes(:children)
respond_with @parents, each_serializer: ::ParentsSerializer, root: false #Not working
end
...
end
#Serializer
class ParentSerializer < ActiveModel::Serializer
attrs = Parent.column_names.map(&:to_sym) - [:options]
attributes(*attrs)
has_many :children
def filter(keys)
keys.delete :children unless object.association(:children).loaded?
keys.add :options
keys
end
end
#模型
类父级[:children]
#是(并且不工作)
@父项=父项。包括(:子项)
用@parents,each_serializer:::parents serializer,root:false#不工作
结束
...
结束
#序列化程序
类ParentSerializer
期望输出
[
{
“家长”:{
“id”:1,
“姓名”:“叔叔”,
“选项”:“无子女,LotsOfLoot”,
“儿童”:[]
}
},
{
“家长”:{
“id”:2,
“姓名”:“妈妈”,
“选项”:“让我惊讶的是,似乎没有直接支持这一点,我不知道您将覆盖什么来添加它。但是解决方法并不坏-只需定义一个自定义的子方法即可:
#Serializer
class ParentSerializer < ActiveModel::Serializer
attrs = Parent.column_names.map(&:to_sym) - [:options]
attributes(*attrs)
has_many :children
def filter(keys)
keys.delete :children unless object.association(:children).loaded?
keys.add :options
keys
end
def children
object.children.collect{|c| ChildSerializer.new(c, scope).as_json(root: :child)}
end
end
#序列化程序
类ParentSerializer
您正在使用children
方法执行ArraySerializer
的工作,但如果没有AM::S的支持,我不确定是否有更干净的方法。我最终使用rabl自定义输出…我想这也可以。我使用了active\u model\u serializer 0.8.1,但不得不对其进行一些更改:attributes:children childrenSerializer.new(c,scope:scope).as_json(root:c.class.name.下划线)
#Serializer
class ParentSerializer < ActiveModel::Serializer
attrs = Parent.column_names.map(&:to_sym) - [:options]
attributes(*attrs)
has_many :children
def filter(keys)
keys.delete :children unless object.association(:children).loaded?
keys.add :options
keys
end
def children
object.children.collect{|c| ChildSerializer.new(c, scope).as_json(root: :child)}
end
end