简体   繁体   English

Rails很快找到记录,其中has_many关联与关联ID数组完全匹配

[英]Rails quickly find record where has_many associations exactly match array of association ids

I've got a Product model which has_many OptionValue records, which describe color , size , etc. 我有一个Product ,其型号has_many OptionValue记录,描述colorsize等。

Within my code, I need to query the Product model where the product.option_values.pluck(:id) array exactly matches an array of (eg) options = [1, 6, 4] . 在我的代码中,我需要查询Product模型,其中product.option_values.pluck(:id)数组与(例如) options = [1, 6, 4] product.option_values.pluck(:id)数组完全匹配。

Running something like Product.includes(:option_values).where(option_values: { id: options_array }) returns all values that match at least one element of the options array, rather than all of them. 运行类似Product.includes(:option_values).where(option_values: { id: options_array })返回与options数组中至少一个元素匹配的所有值,而不是所有值。

I've developed an inefficient way of getting the record I need, as follows: 我开发了一种获取我需要的记录的低效方法,如下所示:

Product.all.each { |v| return v if v.option_values.pluck(:id).sort == options_array.sort }

Obviously the above is way ott and I'm sure there's a simpler way to handle this, and I'm happy to use ActiveRecord or a straight SQL query (though I'm not too hot on the latter, so haven't come up with anything yet). 显然上面的方法是ott,我确信有一种更简单的方法来处理这个问题,我很高兴使用ActiveRecord或直接的SQL查询(虽然我对后者不太热,所以还没有出现什么都没有)。

Any advice on the best way of achieving this greatly appreciated. 关于实现这一目标的最佳方式的任何建议都非常感谢。 Not sure I've explained this perfectly, so please comment if you've any questions. 我不确定我是否完美地解释了这一点,所以如果您有任何疑问请发表评论。

Thanks in advance, Steve. 先谢谢,史蒂夫。

Clocked this in my old questions and threw together a quick and easy solution, so dropping it here for anyone else that might come this way: 在我的旧问题中加入了这个问题,并将一个快速简便的解决方案整合在一起,所以将其放在这里以供其他可能采用这种方式的人:

product_options = product.option_values.pluck(:id)
unless options_array.length < product_options.length
  (product_options & options_array).length == product_options.length
end

This: 这个:

  • checks the options_array is long enough to contain the necessary matches 检查options_array是否足够长以包含必要的匹配
  • looks for the elements in common across the two arrays ( (product_options & options_array) ) 在两个数组中查找共同的元素( (product_options & options_array)
  • measures their length 衡量他们的长度
  • checks this is the same length as the desired array product_options , meaning all the required options were found. 检查这与所需的数组product_options长度相同,这意味着找到了所有必需的选项。

Alternatively, you can subtract one from the other and check there's nothing leftover (ie missing): 或者,您可以从另一个中减去一个,并检查没有剩余(即缺少):

(product_options - options_array).empty?

Hope this helps someone at some point. 希望这在某些方面可以帮助某人。

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

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