简体   繁体   English

ActiveModel序列化器的两个级别属性

[英]ActiveModel Serializers two level attributes

In my rails project, I have one serializer for user: 在我的rails项目中,我为用户提供了一个串行器:

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? 但是用户不包含该项目,因为我猜它太深了,那么我该如何包含它?

You can configure default_includes of AMS for deeper nesting 您可以配置AMS default_includes以进行更深层的嵌套

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

Or you can try to provide include option to render method: 或者,您可以尝试提供include选项以render方法:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM