【问题标题】:ActiveModel::Serializer belongs_to attribute is not being displayed in json responseActiveModel::Serializer belongs_to 属性未显示在 json 响应中
【发布时间】:2016-02-28 01:25:08
【问题描述】:

我不太确定为什么这不起作用,但我有以下序列化程序:

class ExternalAccountSerializer < ActiveModel::Serializer
  attributes :id, :account_name, :type

  belongs_to :user, serializer: UserSerializer
end

API 返回以下内容:

{
    "external_account":{
        "id":3,"account_name":"Company Inc.","type":"External service"
    }
}

正在返回外部帐户,但未返回用户。任何想法为什么会这样?如何确保显示它?

【问题讨论】:

  • 为什么会这样,belongs_to 没有使用序列化器

标签: ruby-on-rails ruby ruby-on-rails-4 activemodel active-model-serializers


【解决方案1】:

我相信您必须在属性中包含 :user:

 attributes :id, :account_name, :type, :user

然后:

def user
  UserSerializer.new(object.user, root: false)
end

【讨论】:

  • 唯一的问题是它不使用自定义序列化程序
  • 你能测试我的版本吗?我正在用 PORO 做类似的事情,不确定它是否适用于你的情况@NickONeill
【解决方案2】:

这是我的解决方案:我必须将用户包含在控制器中。

posts_controller.rb

  ...
  render json: post,
      include: 'user', # include user for custom serializer to work
   serializer: Api::V1::Post::PostSerializer,
       status: :created
猜你喜欢
  • 2014-12-05
  • 1970-01-01
  • 1970-01-01
  • 2015-08-05
  • 1970-01-01
  • 2016-09-27
  • 1970-01-01
  • 1970-01-01
  • 2012-11-02
相关资源
最近更新 更多