Ruby on rails 基于模型的属性动态指定序列化程序
我正在尝试根据父序列化程序中模型的属性动态指定序列化程序:Ruby on rails 基于模型的属性动态指定序列化程序,ruby-on-rails,activemodel,active-model-serializers,Ruby On Rails,Activemodel,Active Model Serializers,我正在尝试根据父序列化程序中模型的属性动态指定序列化程序: ActiveModel::Serializer.setup do |config| config.embed = :ids config.embed_in_root = true end class DocumentSerializer < ActiveModel::Serializer attributes :id, :name, :document_layout if attributes[:docume
ActiveModel::Serializer.setup do |config|
config.embed = :ids
config.embed_in_root = true
end
class DocumentSerializer < ActiveModel::Serializer
attributes :id, :name, :document_layout
if attributes[:document_layout] === 'portrait'
has_many :pages, serializer: PortraitPageSerializer
elsif attributes[:document_layout] === 'landscape'
has_many :pages, serializer: LandscapePageSerializer
end
end
但这似乎不起作用,我想属性不仅仅是散列
是否有其他方法访问该值?还是我完全走错了方向?我在思考这个问题,我已经有一段时间没有研究序列化程序了,这行得通吗
class DocumentSerializer < ActiveModel::Serializer
attributes :id, :name
has_many :portrait_pages, key: pages, serializer: PortraitPageSerializer
has_many :landscape_pages, key: pages, serializer: LandscapePageSerializer
def portrait_pages
pages if object.document_layout === 'portrait'
end
def landscape_pages
pages if object.document_layout === 'landscape'
end
end
这里的另一个选项-将您的文档子类化,以拥有一个LandscapeDocument和一个TorapitalDocument。这可以基于类型,它与文档布局字段对齐。一个想法…您是如何选择DocumentSerializer的?你刚刚渲染了一个文档吗?是的,在我的控制器中我正在调用:render json:@documents,status::ok我想也许使用同一个序列化程序更明智,只是让它根据文档的不同保留一些列为空,我想你是对的。。。Rails STI可能是未来的发展方向,因为它们都可以从基类继承,但是我可以为每种类型使用单独的序列化程序