gpt4 book ai didi

ruby-on-rails - 事件模型序列化程序belongs_to

转载 作者:行者123 更新时间:2023-12-03 10:23:55 26 4
gpt4 key购买 nike

此问题与 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

    关于ruby-on-rails - 事件模型序列化程序belongs_to,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13125214/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com