Rails - 查询has_many关联而不复制我自己

时间:2016-02-13 11:48:13

标签: ruby-on-rails ruby-on-rails-4 rails-activerecord

我们的应用程序中有3个模型:Trips,Destinations和CountryReferences(参考表)。

我们的协会描述如下:

  • 旅行 has_many 目的地
  • 目的地 has_one CountryReference
  • 旅行 has_many CountryReferences 目的地

CountryReference表是使用ISO_2代码作为键将每个国家/地区映射到区域和子区域的引用。例如,泰国将拥有亚洲地区和东南亚次区域。所有关联都经过测试并正常运行。每次旅行还有一个“视图”列。

目标

我们正在尝试创建一个方法,该方法返回一个数组,其中包含每个区域中最受欢迎的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次。我们如何调整此查询以便每次只返回一次?

提前感谢您的帮助!

1 个答案:

答案 0 :(得分:2)

请试试这个。

Trip.joins(:country_references).where('country_references.region' => region, 'published' => true).group('trips.id').order(views: :desc).limit(num_per_region*3)
相关问题