活动模型序列化程序belongs_to [英] Active Model Serializers 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
被序列化时,我想嵌入主题的整个子树.
When a UserCombination
is serialized, I want to embed the whole subtree of subjects.
当我尝试使用此设置时,出现此错误:
When I try to use this setup I get this error:
undefined method `belongs_to' for UserCombinationSerializer:Class
我尝试将 UserCombinationSerializer
更改为:
class UserCombinationSerializer < ActiveModel::Serializer
attributes :id, :subject, :stage
end
在这种情况下,我没有收到任何错误,但是 subject
以错误的方式序列化 - 没有使用 SubjectSerializer
.
In this case I get no errors, but the subject
is serialized in the wrong way - not using the SubjectSerializer
.
我的问题:
- 我不能在序列化程序中使用belongs_to 关系吗?
- 如果不是 - 我怎样才能获得想要的行为 - 使用 SubjectSerializer 嵌入主题树?
推荐答案
这不是很优雅,但似乎有效:
This is not really elegant but it seems to be working :
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
Disregard my comment about has_one/belongs_to ambiguity, the doc is actually pretty clear about it: http://www.rubydoc.info/github/rails-api/active_model_serializers/frames
这篇关于活动模型序列化程序belongs_to的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!