我无法弄清楚如何检索具有深层嵌套关联的ActiveRecord对象。下面是我尝试实现的一个表示为JSON对象的示例。
目前,我的项目模型有:
has_many :groups
has_many :users, through: :groups
has_many :members, through: :groups, source: :users
预期结果(JSON):
{
"id": 7,
"name": "Test Project",
"description": "Project description",
"groups": [
{
"id": 1,
"name": "Test Group 1",
"description": "First test group",
"members": [
{
"id": 1,
"name": "Admin",
"email": "admin@exmaple.com"
},
{
"id": 2,
"name": "Test User",
"email": "test@exmaple.com"
}
]
}
]
}
示例代码:
class Project < ActiveRecord::Base
has_many :groups
has_many :users, through: :groups
has_many :members, through: :groups, source: :users
end
我最接近期望的结果是通过向项目模型添加groups方法来获取所有成员:
最近的结果(JSON):
{
"id": 7,
"name": "Test Project",
"description": "Project description",
"groups": [
{
"id": 1,
"name": "Admin",
"email": "admin@exmaple.com"
},
{
"id": 2,
"name": "Test User",
"email": "test@exmaple.com"
}
]
}
示例代码:
class Project < ActiveRecord::Base
has_many :groups
has_many :users, through: :groups
has_many :members, through: :groups, source: :users
def groups
members.all
end
end
答案 0 :(得分:1)
您可以尝试使用activemodel序列化程序来包含关联的记录。
class ProjectSerializer < ActiveModel::Serializer
attributes :id
has_many :groups
end
class GroupSerializer < ActiveModel::Serializer
attributes :id
has_many :members
end
您可以在以下位置查看:https://github.com/rails-api/active_model_serializers
has_many,has_one和belongs_to声明描述资源之间的关系。默认情况下,当您序列化帖子时,您也将获得其评论。
答案 1 :(得分:0)
你可以这样做:
class Project < ActiveRecord::Base
has_many :groups
has_many :users, through: :groups
has_many :members, through: :groups, source: :users
end
Project.find(7).to_json(include: {groups: {include: :users}})