简体   繁体   English

Rails:选择型号

[英]Rails: select model

I have a model Shop : 我有一个模特Shop

class Shop < ActiveRecord::Base
  has_and_belongs_to_many :services
end

and a model Service : 和模型Service

class Service < ActiveRecord::Base
  has_and_belongs_to_many :shops
end

I would like to query every shop that provides all of the following services: 我想查询所有提供以下所有服务的商店:

  1. Reparation 赔偿
  2. Advise 劝告
  3. Shipping 运输

So return all shops where services contain reparation AND advise AND shipping . 因此,请退还所有包含服务reparation AND advise AND shipping商店,并提供reparation AND advise AND shipping

Is this possible with ActiveRecord querying only? 仅通过ActiveRecord查询可以做到这一点吗?

Thanks! 谢谢!

See MySQL: Select records where joined table matches ALL values for how to do it in sql. 请参阅MySQL:选择联接表匹配所有值的记录,以了解如何在sql中进行操作。

For a simpler method, which makes a series of simple queries instead of a single complex query, you could do this: 对于一个更简单的方法,它执行一系列简单查询而不是单个复杂查询,您可以执行以下操作:

#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)

Key to this is .inject{|a,b| a & b} 关键是.inject{|a,b| a & b} .inject{|a,b| a & b} : inject is an array method which performs a function between the first and second elements (a and b) then uses the result of that with the block again, with the third element etc, working it's way through the array. .inject{|a,b| a & b} :inject是一种数组方法,该方法在第一个元素和第二个元素(a和b)之间执行功能,然后再次将该结果与块一起使用,与第三个元素等一起使用,遍历数组。 The & operator is array intersect, so you will end up only with the shop_ids which are returned for ALL services. &运算符是数组相交的,因此最终只会得到为所有服务返回的shop_id。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM