【发布时间】:2015-06-30 21:45:26
【问题描述】:
我无法弄清楚如何检索具有深度嵌套关联的 ActiveRecord 对象。下面是我试图以 JSON 对象表示的示例。
目前,我的项目模型有:
has_many :groupshas_many :users, through: :groupshas_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
我最接近预期结果的方法是在项目模型中添加一个组方法来获取所有成员:
最近的结果(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
【问题讨论】:
标签: ruby-on-rails ruby activerecord associations model-associations