Active_model_serializers: has_one association not included in rendered json

Created on 24 Oct 2016  路  6Comments  路  Source: rails-api/active_model_serializers

Expected behavior vs actual behavior

Parking has_many :cars
Car has_one :driver

class ParkingSerializer < ActiveModel::Serializer
  attributes :id, :location
  has_many :cars
end
class CarSerializer < ActiveModel::Serializer
  attributes :id, :brand
  has_one :driver
end
class DriverSerializer < ActiveModel::Serializer
  attributes :id, :name
end

Expected
A driver nested under each car in the json when rendering a parking

Result
json with parking's attributes, cars, cars attributes except driver

Steps to reproduce

See serializers above

Controller:

# ...
def show
  @parking = Parking.find(params[:id])
  render json: @parking
end
# ...

Environment

ActiveModelSerializers Version 0.10.2
ruby 2.2.3p173 (2015-08-18 revision 51636) [x86_64-darwin15]
macOS Sierra
Rails 4.2.7.1

Most helpful comment

@prrrnd try:

render json: @parking, include: "*.*"

With 0.10, associations are included by default only for the first level. If you want to include deeper associations, you need to specify it with the include directive. In this case, include: "*.*" means include any association up to 2 levels. You may also use include: ** to include every level (not recommended) or be more specific include: "cars.driver".

All 6 comments

Json adapter?

@beauby I'm using the default one, :attributes
Also worth noting, 0.9.5 works fine, the issue appears when I upgrade to 0.10.2

@prrrnd try:

render json: @parking, include: "*.*"

With 0.10, associations are included by default only for the first level. If you want to include deeper associations, you need to specify it with the include directive. In this case, include: "*.*" means include any association up to 2 levels. You may also use include: ** to include every level (not recommended) or be more specific include: "cars.driver".

@groyoh Thanks, I'll try that and report back.
Seems like your explanation could be part of the documentation, it's waiting for a PR.

@prrrnd yeah the documentation is definitely lacking some love. If this was helpful for you, maybe you would kind enough to help us out with the doc :smile:

@groyoh The include directive definitely helped. I'll try to update the documentation in a PR.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

kapso picture kapso  路  4Comments

greggawatt picture greggawatt  路  4Comments

Tybot204 picture Tybot204  路  3Comments

adamcrown picture adamcrown  路  4Comments

PratheepV picture PratheepV  路  4Comments