简体   繁体   English

Active Record按ID查找

[英]Active Record find by ids

How can I compose a query to find records by the ids I'm passing? 如何编写查询以通过传递的ID查找记录? Currently I query them with this command Model.where(id: [1,2,3]) . 当前,我使用此命令Model.where(id: [1,2,3])查询它们。 Everything works fine, but this is not the behavior I want. 一切正常,但这不是我想要的行为。 The case is that if there is no record with id=3 it will return results for id=1 or 2 and I need to return the results only when all ids are found or return nothing. 情况是,如果没有id = 3的记录,它将返回id = 1或2的结果,而我仅在找到所有id时才返回结果,或者什么也不返回。

this will be one of the ways 这将是方法之一

ids = [1,2,3]
records = Model.where(id: ids) 

result = records.count == ids.count ? records : []
User.find([1,3,4]).count
  User Load (0.4ms)  SELECT `users`.* FROM `users` WHERE `users`.`id` IN (1, 3, 4)
=> 3

User.find([1,2,4]).count
  User Load (0.8ms)  SELECT `users`.* FROM `users` WHERE `users`.`id` IN (1, 2, 4)
ActiveRecord::RecordNotFound: Couldn't find all Users with IDs (1, 2, 4) (found 2 results, but was looking for 3)

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

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