【问题标题】:Rails Active_Model_Serializer Relationships not beeing serializedRails Active_Model_Serializers 关系未序列化
【发布时间】:2017-07-17 11:29:33
【问题描述】:

我正在使用 active_model_serializer gem 构建 Rails API。

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

首先,这是我的模型:

用户.rb

class User < ApplicationRecord
has_many :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”,所有属性都列在关系属性的“组件”下,如第二个屏幕截图所示。

JSON Request without component_serializer.rb

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

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

提前致谢

【问题讨论】:

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


    【解决方案1】:

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

    Active Model Serializers data attributes from associations are not loading

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


    只是一个快速更新。如果其他人遇到这个问题。

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

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

    【讨论】:

      猜你喜欢
      • 2020-04-15
      • 2023-04-06
      • 2017-03-03
      • 2016-07-16
      • 2022-01-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-22
      相关资源
      最近更新 更多