Rails: select 模型

Rails: select model

我有一个模型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. 运费

所以 return 所有服务包含 reparation AND advise AND shipping.

的商店

仅使用 ActiveRecord 查询是否可行?

谢谢!

请参阅 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 & b}:inject 是一种数组方法,它在第一个和第二个元素(a 和 b)之间执行一个函数,然后再次使用该块的结果,第三个元素等等,通过数组工作。 & 运算符是数组相交的,因此您最终只会得到为所有服务返回的 shop_ids。