【发布时间】: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