如何从 Rails ActiveModelSerializers return 父数据?

How to return parent data from Rails ActiveModelSerializers?

如何 return 来自 Rails ActiveModelSerializers 的父数据?

这是我的模特

class User < ActiveRecord::Base

  has_many :user_groups ,dependent: :destroy
  has_many :groups , through: :user_groups

end

class Group < ActiveRecord::Base

  has_many :user_groups ,dependent: :destroy
  has_many :users , through: :user_groups

end

class UserGroup < ActiveRecord::Base

  belongs_to :user
  belongs_to :group

end

这是我的序列化程序

class UserSerializer < ActiveModel::Serializer
  attributes :id ,:email, :username, :fullname, :grade,:auth_token

  has_many :user_groups

end

class GroupSerializer < ActiveModel::Serializer
  attributes :id ,:name ,:court_price ,:shuttle_price
  has_many :user_groups
end

class UserGroupSerializer < ActiveModel::Serializer
  attributes :id , :level

  belongs_to :user_id

end

这是我的控制器

def member_list
  group = current_user.groups.find_by(id: params[:id])

  respond_with group
end

所以我想 return 用户组数据里面有用户数据,但这就是我得到的。

{
  "id": 35,
  "name": "test 01",
  "court_price": 150,
  "shuttle_price": 12,
  "user_groups": [
    {
      "id": 30,
      "level": "player"
    },
    {
      "id": 29,
      "level": "owner"
    }
  ]
}

如何在 user_groups 数组中 return 用户数据? 谢谢!

你必须小心那里的循环引用。 Group 嵌入 UserGroup,嵌入 User,也嵌入 UserGroup

对于这种情况,我建议为没有关系的用户创建自定义序列化程序。例如,ShallowUserSerializer。

class ShallowUserSerializer < ActiveModel::Serializer
  attributes :id ,:email, :username, :fullname, :grade,:auth_token
end

除此之外,UserGroupSerializer 有一个小问题。 active_model_serializer 的文档状态:

Serializers are only concerned with multiplicity, and not ownership. belongs_to ActiveRecord associations can be included using has_one in your serializer.

所以你可以这样重写它:

class UserGroupSerializer < ActiveModel::Serializer
  attributes :id , :level
  has_one :user, serializer: ShallowUserSerializer
end