通过ID查找Active Record

时间:2014-08-20 09:20:06

标签: sql ruby-on-rails activerecord

我如何撰写查询以通过我传递的ID查找记录? 目前我使用此命令Model.where(id: [1,2,3])查询它们。一切正常,但这不是我想要的行为。情况是,如果没有id = 3的记录,它将返回id = 1或2的结果,并且我只需要在找到所有id时返回结果或者不返回任何内容。

2 个答案:

答案 0 :(得分:5)

这将是其中一种方式

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

result = records.count == ids.count ? records : []

答案 1 :(得分:0)

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)