Ruby on rails 活动模型序列化程序属于\u

Ruby on rails 活动模型序列化程序属于\u,ruby-on-rails,active-model-serializers,Ruby On Rails,Active Model Serializers,此问题与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 我尝试将UserCombinationSerialize

此问题与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
我尝试将
UserCombinationSerializer
更改为:

class UserCombinationSerializer < ActiveModel::Serializer
  attributes :id, :subject, :stage
end
class UserCombinationSerializer
在这种情况下,我没有得到任何错误,但是
主题
以错误的方式序列化-没有使用
主题序列化程序

我的问题是:

  • 我不应该在序列化程序中使用归属关系吗
  • 如果没有-我如何获得想要的行为-使用SubjectSerializer嵌入主题树

  • 这不是很优雅,但似乎很有效:

    class UserCombinationSerializer < ActiveModel::Serializer
      attributes :id, :stage_id, :subject_id
    
      has_one :subject
    end
    
    class UserCombinationSerializer
    我真的不喜欢打电话,因为它实际上是一个属于协会的组织:/


    编辑:忽略我关于has_one/belies_的评论,文档实际上对此非常清楚:

    如果您尝试这样做会怎么样:

    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
    
    class UserCombinationSerializer
    在活动模型序列化程序0-10-stable中,
    所属的
    现在可用

    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
    
    class UserCombinationSerializer
    好的,是的,这很有效。我想我现在更了解
    的方法了。在
    序列化程序中
    ,唯一有趣的是一个方法是否返回一个或多个对象。所以区分“有一个”和“属于”并不有趣。措辞与ActiveRecord术语相吻合有点不太理想,因为术语的含义并不相同。我最近遇到了同样的问题。是的,使用has_one:属性对我很有用。
    ActiveModel::Serializer
    的文档明确指出:“序列化程序只涉及多重性,而不涉及所有权。属于ActiveRecord的关联可以在序列化程序中使用has_one包含。”@awendt我可以问一下,这是在哪里明确说明的吗?我好像找不到。我并不是说你错了,我还是rails/ruby的新手,在查找文档方面并没有Java那么出色和快速。这就引出了真正的问题,如果不明显的话,它是不明确的。@Andy根据我的经验,遗憾的是,没有找到文档的中心位置。很多人在ruby文档上有文档,很多人在github上有文档,不幸的是,很多人也没有。大多数时候,我在谷歌上花了很多时间。
    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