我無法弄清楚如何檢索具有深度嵌套關聯的ActiveRecord對象。下面是我試圖用JSON對象表達的一個例子。檢索深度嵌套的ActiveRecord關聯
目前,我的項目模型有:
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": "[email protected]"
},
{
"id": 2,
"name": "Test User",
"email": "[email protected]"
}
]
}
]
}
示例代碼:
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": "[email protected]"
},
{
"id": 2,
"name": "Test User",
"email": "[email protected]"
}
]
}
示例代碼:
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
這是完美的!謝謝。我們一直在使用序列化器,但我不認爲我完全理解它們。我的意思是,我仍然沒有,但在這種情況下你肯定幫助我理解他們。謝謝! – OBCENEIKON
歡迎您。我認爲你可以從閱讀序列化開始:https://en.wikipedia.org/wiki/Serialization >在計算機科學中,在數據存儲的上下文中,序列化是將數據結構或對象狀態轉換爲格式,可以存儲(例如,在文件或內存緩衝區中,或通過網絡連接鏈接傳輸),稍後在同一個或另一個計算機環境中重新構建。 – adantj