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次。我们如何调整这个查询,以便每次旅行只返回一次?
在此先感谢您的帮助!