【问题标题】:Rails - Query has_many Association without Duplicating MyselfRails - 在不复制自己的情况下查询 has_many 关联
【发布时间】:2016-02-13 11:48:12
【问题描述】:

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

我们的关联描述如下:

  • 旅行有_many 目的地
  • 一个目的地 has_one CountryReference
  • 旅行有_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 次。我们如何调整这个查询,让每个行程只返回一次?

提前感谢您的帮助!

【问题讨论】:

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


    【解决方案1】:

    请试试这个。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多