2017-04-06 87 views
0

我有以下型號:Rails的LEFT JOIN搜索和JSON

class Address < ActiveRecord::Base 
    has_many :service_records 
    attr_accessor :service_record 
end 

class ServiceRecord < ActiveRecord::Base 
    belongs_to :address 
    belongs_to :plant 
end 

class Plant < ActiveRecord::Base 
    has_one :service_record 
end 

我想執行一個查詢,左連接上的地址的每個服務記錄和服務記錄每個工廠。因此,例如,如果我有一個具有3個服務記錄的地址,我想獲得3個結果,這些結果爲每個服務記錄重複地址字段,同時還包含每個服務記錄的工廠信息。

到目前爲止,我有我的查詢看起來像這樣(使用Rails 5):

Address.left_joins(service_records: :plant) 

返回我重複地址結果的正確數量(即3從我上面的例子)。

下一步我很努力的想找到的結果是將返回的查詢返回爲包含每個地址和每個唯一服務記錄的JSON結構。因此,像這樣:

[ 
    { 
    id: 1, 
    address: "1234 Street Rd", 
    service_record: { 
     id: 1 
     plant: { 
     id: 1 
     } 
    } 
    }, 
    { 
    id: 1, 
    address: "1234 Street Rd", 
    service_record: { 
     id: 2 
     plant: { 
     id: 2 
     } 
    } 
    }, 
    { 
    id: 1, 
    address: "1234 Street Rd", 
    service_record: { 
     id: 3 
     plant: { 
     id: 3 
     } 
    } 
    } 
] 

如果你發現,我有我的地址模型的attr_accessor :service_record,但我不知道這是正確的做法得到我所需要的。任何幫助或替代方法來獲得我正在尋找的將非常感激!

回答

0

從您的查詢中,您可以使用帶選項的Rails as_json來實現您想要的功能。你可以做這樣的事情:

addresses = Address.left_joins(service_records: :plant) 
addresses.as_json 
# => [ 
    { 
    id: 1, 
    address: "1234 Street Rd" 
    }, 
    { 
    id: 1, 
    address: "1234 Street Rd" 
    }, 
    { 
    id: 1, 
    address: "1234 Street Rd" 
    } 
] 

下一步是包括協會

addresses.as_json(include: :service_record) 
[ 
    { 
    id: 1, 
    address: "1234 Street Rd", 
    service_record: { 
     id: 1 
    } 
    }, 
    { 
    id: 1, 
    address: "1234 Street Rd", 
    service_record: { 
     id: 2 
    } 
    }, 
    { 
    id: 1, 
    address: "1234 Street Rd", 
    service_record: { 
     id: 3 
    } 
    } 
] 

最後:

addresses.as_json(include: { service_record: { include: :plant } }) 
# => [ 
    { 
    id: 1, 
    address: "1234 Street Rd", 
    service_record: { 
     id: 1 
     plant: { 
     id: 1 
     } 
    } 
    }, 
    { 
    id: 1, 
    address: "1234 Street Rd", 
    service_record: { 
     id: 2 
     plant: { 
     id: 2 
     } 
    } 
    }, 
    { 
    id: 1, 
    address: "1234 Street Rd", 
    service_record: { 
     id: 3 
     plant: { 
     id: 3 
     } 
    } 
    } 
] 

然後,您可以微調的結果。更多關於documentation

UPDATE

如果你確信你將有service_records陣列中只有一條記錄,你可以這樣做:

def service_record 
    service_records.first 
end 

然後做到這一點

addresses.as_json(methods: :service_record) 
[ 
    { 
    id: 1, 
    address: "1234 Street Rd", 
    service_record: { 
     id: 1 
    } 
    }, 
    { 
    id: 1, 
    address: "1234 Street Rd", 
    service_record: { 
     id: 2 
    } 
    }, 
    { 
    id: 1, 
    address: "1234 Street Rd", 
    service_record: { 
     id: 3 
    } 
    } 
] 
+0

'service_record'不是地址模型上的「官方」屬性。我只能訪問'service_records',因爲這是模型之間的關聯。 –

+0

你爲什麼設置service_record attr_accessor? – Jeremie

+0

我補充說,這是一個可能的想法。我目前沒有設置任何地方。我希望有一種方法可以設置等同於在查詢過程中加入地址的'service_record',但看起來這是不可能的。 –