0

我無法弄清楚如何檢索具有深度嵌套關聯的ActiveRecord對象。下面是我試圖用JSON對象表達的一個例子。檢索深度嵌套的ActiveRecord關聯

目前,我的項目模型有:

  1. has_many :groups
  2. has_many :users, through: :groups
  3. 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 

回答

1

你可以嘗試使用activemodel的serializ包括相關記錄。

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

這是完美的!謝謝。我們一直在使用序列化器,但我不認爲我完全理解它們。我的意思是,我仍然沒有,但在這種情況下你肯定幫助我理解他們。謝謝! – OBCENEIKON

+0

歡迎您。我認爲你可以從閱讀序列化開始:https://en.wikipedia.org/wiki/Serialization >在計算機科學中,在數據存儲的上下文中,序列化是將數據結構或對象狀態轉換爲格式,可以存儲(例如,在文件或內存緩衝區中,或通過網絡連接鏈接傳輸),稍後在同一個或另一個計算機環境中重新構建。 – adantj

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}})