【发布时间】:2020-04-12 14:58:32
【问题描述】:
我开始使用gem 'active_model_serializers', '~> 0.10.0'。关注this 文档
为实施。
我有以下关系。
landmark has_many concerns
concern belongs_to landmark
concern has_many comments
我在app/serializers/api/application_serializer.rb 创建了一个ApplicationSerializer
module API
class ApplicationSerializer < ActiveModel::Serializer
# some commode here
end
end
我的关注序列化器包含:
# ===> Does not work <=====
module API::V1
class ConcernSerializer < ApplicationSerializer
attributes :id, :body
has_many :comments
belongs_to :landmark
class CommentSerializer < ApplicationSerializer
attributes :id, :body
end
class LandmarkSerializer < ApplicationSerializer
attributes :id, :short_address
end
end
end
# ====> However, this works <====
module API::V1
class ConcernSerializer < ApplicationSerializer
attributes :id, :body
has_many :comments
class CommentSerializer < ActiveModel::Serializer
attributes :id, :body
end
end
end
# ===> Does not work again<=====
module API::V1
class ConcernSerializer < ApplicationSerializer
attributes :id, :body
has_many :comments
belongs_to :landmark
class CommentSerializer < ActiveModel::Serializer
attributes :id, :body
end
class LandmarkSerializer < ActiveModel::Serializer
attributes :id, :short_address
end
end
end
在上面的代码中,如果我将ApplicationSerializer 替换为ActiveModel::Serializer,它可以正常工作,但我会丢失ApplicationSerializer 中定义的通用代码。
【问题讨论】:
标签: ruby-on-rails active-model-serializers