Rails Active_Model_Serializer关系不是序列化的

时间:2017-02-26 23:59:50

标签: ruby-on-rails ruby serialization ruby-on-rails-5 active-model-serializers

我正在使用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

正如您在附图中看到的那样,我可以序列化“用户”的属性,但无法编辑“组件”的属性。

JSON Request with component_serializer.rb

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

JSON Request without component_serializer.rb

我错过了什么吗?我现在搜索了很长时间但没找到答案。

不知道这是否重要,但我在Linux服务器上使用Rails 5.0.1,使用'active_model_serializers','〜&gt; 0.10.0'宝石。

提前致谢

1 个答案:

答案 0 :(得分:0)

好好搜索一下后,我发现,这个问题已经被提出了^^

Active Model Serializers data attributes from associations are not loading

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

快速更新。如果其他人正在解决这个问题。

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

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