0
我們在我們的應用程序中有3個模型:旅程,目的地和國家參考(參考表)。Rails - 查詢has_many沒有複製我自己的協會
我們的關聯描述如下:
- 甲旅行的has_many 目的地
- 甲目的地 HAS_ONE CountryReference
- 甲旅行的has_many CountryReferences通過個目的地
的CountryReference表是每個國家映射到一個區域和子區域使用ISO_2代碼作爲密鑰的參考。例如,泰國將擁有亞洲的一個地區和東南亞的一個次地區。所有的協會都經過測試和正常工作。每個Trip還有一個「視圖」列。
我們試圖創建與6最流行的(#的視圖)返回一個陣列的方法的目標時刻表在每個區域中。我們希望避免重複旅行,也就是說,如果行程跨越多個區域,我們只想將其添加到數組中。
我們的代碼
#returns a an array of trips, this array should contain at least 'num_per_region' trips per region
def self.popular_by_region(num_per_region)
regions = []
regions.push 'Asia'
regions.push 'Europe'
regions.push 'Africa'
regions.push 'Central America and the Caribbean'
regions.push 'South America'
regions.push 'Australia and Oceania'
regions.push 'North America'
trips_array = []
trips_hash = {} #used to figure out if trip has already been added to array
#load 6 most popular trips per region
regions.each do |region|
region_trips = Trip.joins(:country_references).where('country_references.region' => region, 'published' => true).order(views: :desc).limit(num_per_region*3)
region_trips.each do |trip|
if trips_hash[trip.id].nil?
trips_hash[trip.id] = 1
trips_array.push trip
end
end
end
return trips_array
end
的問題
ActiveRecord的查詢Trip.join...
回報每一次跳閘目的地。也就是說,如果我的旅程有5個目的地,全部在亞洲,那麼同樣的旅程將返回5次。我們如何調整這個查詢,以便每次旅行只返回一次?
在此先感謝您的幫助!