【问题标题】:active model serializer not showing all attributes of associated model活动模型序列化程序未显示关联模型的所有属性
【发布时间】:2017-05-18 22:17:17
【问题描述】:

我有一个项目。它属于一个用户。我在 app/serializers 中有一个 ItemSerializer 和一个 UserSerializer:

class ItemSerializer < ActiveModel::Serializer
  attributes :id, :photo

  belongs_to :user
end

class UserSerializer < ActiveModel::Serializer
  attributes :id, :email, :authentication_token
end

这些关系对 app/models 中的关系进行建模

当我在控制器中以 json 形式返回 ActiverRecord::Relation 时:

def index
    respond_to do |format|
      @items = Item.where(id: params[:item_ids)
      format.html
      format.json { render json: @items, status: 200}
    end
  end

它还应该返回用户属性,包括电子邮件和 authentication_token。但它只返回用户 ID:

... "relationships":{"user":{"data":{"id":"1","type":"users"}}} ...

我做错了什么?

【问题讨论】:

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


    【解决方案1】:

    试试看

    render json: @items, include: "**", status: 200
    

    在您的控制器中。 AMS 在返回相关对象属性时可能很挑剔,因此有时您需要明确说明。

    【讨论】:

    • 我不知道这是否有效,但请查看我的解决方案。问题是我使用 json_api 而不是 json 作为适配器。
    【解决方案2】:

    我发现了这个问题。我正在使用 active_model_serializers 版本 0.10.0。在config/environments/initialzers/active_model_serializer.rb,我有如下配置:

    ActiveModel::Serializer.config.adapter = :json_api
    

    当我把它改成:

    ActiveModel::Serializer.config.adapter = :json
    

    它也给了我关联的属性,如控制台所示:

    ActiveModelSerializers::SerializableResource.new( Item.where(id: params[:item_ids), adapter: :json).to_json
    

    【讨论】:

    • adapter json_api 支持精确的jsonapi标准格式,当我们将adapter改为json时,它会给出正常格式。
    猜你喜欢
    • 2016-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多