Search code examples
ruby-on-railsactive-model-serializers

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?


Solution

  • 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"]