Rails Active_Model_Serializer 关系未被序列化

Rails Active_Model_Serializer Relationships not beeing serialized

我正在用 active_model_serializer gem 构建一个 Rails API。

我遇到的问题是,即使我为它们创建了序列化程序,我也无法序列化关系。

首先,这是我的模型:

user.rb

class User < ApplicationRecord
has_many :component

component.rb

class Component < ActiveRecord::Base
  belongs_to :user

  has_many :profiles
end

这是我的 users_controller.rb:

class UsersController < ApplicationController

    def show
        @user = User.first

        render(                              //
            status: :ok,                     //
            json: @user,                     //updated
            serializer: UserSerializer       //
        )                                    //
    end
end

还有我的序列化程序。

user_serializer.rb

class UserSerializer < ApplicationSerializer
  attributes :id, :component

  has_many :component, serializer: ComponentSerializer //updated
end

component_serializer.rb

class ComponentSerializer < UserSerializer
  attribute :id, :profile, :test

  def test
    'this is a test'
  end
end

正如您在附图中看到的,我可以序列化 'User' 的属性,但无法编辑 'component'.

的属性

JSON Request with component_serializer.rb

如果我删除文件 'component_serializer.rb' 所有属性都列在关系属性的 'component' 下,如第二个屏幕截图所示。

JSON Request without component_serializer.rb

我错过了什么吗?我现在搜索了一段时间,但没有找到答案。

不知道这是否重要,但我在 linux 服务器上使用 Rails 5.0.1,'active_model_serializers','~> 0.10.0' gem.

提前致谢

好吧,搜索了一会儿,我才发现,这个问题已经被问过了^^

谁能告诉我这是否是序列化嵌套模型的推荐方法?


只是一个快速更新。如果别人是运行这个问题。

这篇来自 GoRails 的教程解释了为什么序列化程序不影响模型关系中的属性以及如何包含嵌套模型。

https://www.youtube.com/watch?v=lQOLrycmXC4