2017-05-18 43 views
1

我有一个项目。它属于用户。我有一个ItemSerializer和应用程序/串行一个UserSerializer:活动模型序列化程序未显示关联模型的所有属性

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

    belongs_to :user 
end 

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

这些关系模型在app /关系模型

当我在我的控制器返回项目的ActiverRecord ::关系为JSON:

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

它应该返回用户属性,包括email和authentication_token。但它只返回用户ID:

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

我在做什么错?

回答

1

尝试做

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

在您的控制器。 AMS可以在返回相关的对象属性时挑剔,所以有时你需要明确它的含义。

+0

我不知道这是否有效,但看看我的解决方案。问题是我使用json_api而不是json作为适配器。 – Donato

1

我想通了这个问题。我正在使用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 
相关问题