【问题标题】:Rails: select model导轨:选择型号
【发布时间】:2015-06-18 14:29:46
【问题描述】:

我有一个模特Shop:

class Shop < ActiveRecord::Base
  has_and_belongs_to_many :services
end

还有一个模特Service:

class Service < ActiveRecord::Base
  has_and_belongs_to_many :shops
end

我想查询每家提供所有以下服务的商店:

  1. 赔偿
  2. 建议
  3. 运费

所以返回所有服务包含reparation AND advise AND shipping的商店。

这是否可以仅通过 ActiveRecord 查询实现?

谢谢!

【问题讨论】:

  • 这需要硬编码的 SQL 查询,而不仅仅是 ActiveRecord。因为Shop.includes(:services).where(services: { name: ['reparation', 'advise', 'shipping'] }) 将返回至少具有 3 项服务中的一项的商店(OR 条件,而不是您所要求的 AND)。

标签: sql ruby-on-rails activerecord associations


【解决方案1】:

请参阅MySQL: Select records where joined table matches ALL values 了解如何在 sql 中执行此操作。

对于一个更简单的方法,它会进行一系列简单查询而不是单个复杂查询,您可以这样做:

#starting with the services in an array called @services
#(which could come from params[:service_ids] for example)
#find shops which have ALL these services.
shop_ids = @services.map(&:shop_ids).inject{|a,b| a & b}
@shops = Shop.find(shop_ids)

这个的关键是.inject{|a,b| a &amp; b}:inject 是一个数组方法,它在第一个和第二个元素(a 和 b)之间执行一个函数,然后再次将结果与块一起使用,第三个元素等等,工作通过阵列的方式。 &amp; 运算符是数组相交的,因此您最终只会得到所有服务返回的 shop_id。

【讨论】:

  • 这太棒了。谢谢!
猜你喜欢
  • 2010-11-01
  • 2010-11-18
  • 2013-08-08
  • 1970-01-01
  • 2014-03-15
  • 2010-12-07
  • 1970-01-01
  • 1970-01-01
  • 2013-06-13
相关资源
最近更新 更多