活动模型序列化程序belongs_to
这个问题与AMS 0.8有关
我有两个型号:
class Subject < ActiveRecord::Base has_many :user_combinations has_ancestry end class UserCombination < ActiveRecord::Base belongs_to :stage belongs_to :subject belongs_to :user end
还有两个序列化器:
class UserCombinationSerializer < ActiveModel::Serializer attributes :id belongs_to :stage belongs_to :subject end class SubjectSerializer < ActiveModel::Serializer attributes :id, :name, :description, :subjects def include_subjects? object.is_root? end def subjects object.subtree end end
当UserCombination
被序列化时,我想嵌入整个主题子树。
当我尝试使用此设置时,我收到此错误:
undefined method `belongs_to' for UserCombinationSerializer:Class
我尝试将UserCombinationSerializer
更改为:
class UserCombinationSerializer < ActiveModel::Serializer attributes :id, :subject, :stage end
在这种情况下,我没有错误,但subject
是以错误的方式序列化 – 不使用SubjectSerializer
。
我的问题:
- 我不应该在序列化器中使用belongs_to关系吗?
- 如果不是 – 我怎样才能获得想要的行为 – 使用SubjectSerializer嵌入主题树?
这不是很优雅,但它似乎工作:
class UserCombinationSerializer < ActiveModel::Serializer attributes :id, :stage_id, :subject_id has_one :subject end
我真的不喜欢调用has_one,而它实际上是一个belongs_to关联:/
编辑:忽略我关于has_one / belongs_to歧义的评论,该文档实际上非常清楚: http : //www.rubydoc.info/github/rails-api/active_model_serializers/frames
如果你尝试这样的事情怎么办?
class UserCombinationSerializer < ActiveModel::Serializer attributes :subject, :stage, :id def subject SubjectSerializer.new(object.subject, { root: false } ) end def stage StageSerializer.new(object.stage, { root: false } ) end end
在Active Model Serializer 0-10-stable中, belongs_to
现在可用。
belongs_to :author, serializer: AuthorPreviewSerializer belongs_to :author, key: :writer belongs_to :post belongs_to :blog def blog Blog.new(id: 999, name: 'Custom blog') end
所以你可以这样做:
class UserCombinationSerializer < ActiveModel::Serializer attributes :id belongs_to :stage, serializer: StageSerializer belongs_to :subject, serializer: SubjectSerializer end
- Url Helper在ActiveModelSerializer 0.10.0中?
- 控制器中的索引方法不适用于活动模型序列化程序
- 使用active_model_serializers序列化权限(例如CanCan)
- 如何在active_model_serializers中执行预先加载
- 如何为活动模型序列化器关系选择所需的属性
- 使用active_model_serializers序列化模型数组
- Rails ActiveModelSerializer将两个相同类型模型的列表组合成一个序列化响应,具有不同的名称
- 如何使用active_model_serializers为嵌套对象选择序列化程序
- ActiveModel Serializers:has_many在运行时有条件吗?