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
,但我不知道這是正確的做法得到我所需要的。任何幫助或替代方法來獲得我正在尋找的將非常感激!
'service_record'不是地址模型上的「官方」屬性。我只能訪問'service_records',因爲這是模型之間的關聯。 –
你爲什麼設置service_record attr_accessor? – Jeremie
我補充說,這是一個可能的想法。我目前沒有設置任何地方。我希望有一種方法可以設置等同於在查詢過程中加入地址的'service_record',但看起來這是不可能的。 –