找到你要的答案

Q:ActiveRecord return uniq item by title condition nearest distance

Q:他返回uniq项目的标题下最近的距离

I have following relation, because same product can exist in multiple stores, so DB stores the same product record in database with different store_id for each store, I also stores the coords for each product, now my query returns duplicate products by title for each store.

For quick fix how can I modify the query to it returns the closest products only and group by the product title maybe. BTW I am using geocode gem and near function to select nearby product near([@lat, @long], 20, order: @sort.blank? ? 'distance' : false)

class Product < ActiveRecord::Base
   belongs_to :store
end

class Store < ActiveRecord::Base
   has_many :products
end

ID TITLE   STORE_ID
1  product_1  1
2  product_1  2
3  product_1  3

4  product_2  1
5  product_2  2
6  product_2  3

我有以下的关系,因为同样的产品可以在多个商店的存在,所以数据库存储每个存储在不同store_id数据库相同的产品记录,我还存储坐标的每个产品,现在我的查询返回重复的产品由各店的称号。

对于快速修复,我如何修改查询到它返回的最接近的产品和小组的产品称号也许。顺便说一句,我用宝石和地理编码功能选择产品附近附近附近([ @ LAT,@长],20,命令:@sort.blank?“距离”:假)

class Product < ActiveRecord::Base
   belongs_to :store
end

class Store < ActiveRecord::Base
   has_many :products
end

ID TITLE   STORE_ID
1  product_1  1
2  product_1  2
3  product_1  3

4  product_2  1
5  product_2  2
6  product_2  3
answer1: 回答1:

I think you have a misconception in your model. If the same product can be in several stores, then A product does NOT belong to a store. Cause it could be in several.

You should change your associations to a has_and_belongs_to_many or a has_many through one. But if you really want this query done, you can use the group method in your query. Like Product.near(...).group(:title)

You can also filter after in Rails. Assuming it's already an ordered set, something like

@products.to_a.uniq(&:title)

would work.

我认为你对你的模型有误解。如果同一产品可以在多个商店,那么一个产品不属于商店。原因可能是在几个。

You should change your associations to a has_and_belongs_to_many or a has_many through one. But if you really want this query done, you can use the group method in your query. Like Product.near(...).group(:title)

您也可以过滤后在轨道。假设它已经是一个有序集,类似的东西

@products.to_a.uniq(&:title)

将工作。

ruby-on-rails  postgresql  activerecord