rablentain
rablentain

Reputation: 6715

ActiveModel Serializers two level attributes

In my rails project, I have one serializer for user:

class UserSerializer < ActiveModel::Serializer
    attributes ...
    has_one :project
    has_many :sessions
end

and one for session:

class SessionSerializer < ActiveModel::Serializer
    attributes ...
    belongs_to :user
end

So if I return the session from any controller:

render json: session

I get something like:

{ "session": {
    "user: { ... }
    ...
}

but user does not contain the project, because it's too deep I guess, so how do I include that?

Upvotes: 1

Views: 428

Answers (1)

Igor Drozdov
Igor Drozdov

Reputation: 15045

You can configure default_includes of AMS for deeper nesting

# config/initializers/active_model_serializer.rb
ActiveModel::Serializer.config.default_includes = '**'

Or you can try to provide include option to render method:

render json: session, include: ["user.project"]

Upvotes: 2

Related Questions