Ruby on rails 将多个ActiveRecord子数组合并为一个?

Ruby on rails 将多个ActiveRecord子数组合并为一个?,ruby-on-rails,ruby-on-rails-4,rails-activerecord,Ruby On Rails,Ruby On Rails 4,Rails Activerecord,我有两种型号: class Location < ActiveRecord::Base has_many :products end class Product < ActiveRecord::Base belongs_to :location end 是否可以将所有产品连接到一个数组中,同时清除所有重复的产品ID,而不必担心它最初属于哪个位置?在代码中,您只返回一个位置。你是说地点吗?在哪里城市:奥兰多?假设你这样做,我会考虑这样做: location_ids

我有两种型号:

class Location < ActiveRecord::Base
    has_many :products
end

class Product < ActiveRecord::Base
    belongs_to :location
end

是否可以将所有产品连接到一个数组中,同时清除所有重复的产品ID,而不必担心它最初属于哪个位置?

在代码中,您只返回一个位置。你是说地点吗?在哪里城市:奥兰多?假设你这样做,我会考虑这样做:

location_ids = Location.where(city: "Orlando").pluck(:id)
products = Product.where(location_id: location_ids)
您也可以使用连接来执行此操作:

products = Product.joins(:location).where(location: {city: "Orlando"})

或者,如果您希望以后可以使用位置,请切换到includes。

好的,您可以使用来解决它,只需记住产品的关联名为location,而不是locations。我不确定它是否重复,但非常接近。为什么产品中的id会重复?多个位置有相同的产品。百思买也有同样的索尼电视就是一个例子。
products = Product.joins(:location).where(location: {city: "Orlando"})