【问题标题】:what is the equivalent of "find_all_by_id" in rails 4rails 4中“find_all_by_id”的等价物是什么
【发布时间】:2015-08-06 22:51:51
【问题描述】:

我有一个 id 数组,我想使用活动记录查询从数据库中找到它们各自的记录。例如:ids = [2, 3, 1]

现在,我要查找特定模型的所有记录,其 id 是数组中的一个,在较低版本的 rails 中,我想我可以执行以下操作:

Model.find_all_by_id([2, 3, 1])

但是根据this post

These methods were deprecated on 4.0 and removed at 4.1. If you want to
keep sing then you need to include this gem
https://github.com/rails/activerecord-deprecated_finders

我的问题是,我没有办法在 rails4.2 中做到这一点而不必包含一个 gem?

谢谢。

【问题讨论】:

标签: ruby-on-rails ruby-on-rails-4 activerecord


【解决方案1】:

这应该可行:

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

【讨论】:

  • 对我来说它只返回一条记录!!
【解决方案2】:

officially proposed alternativeModel.where(id: [2, 3, 1])

# There are 3 users in the db, with ids 1, 2, and 3
> User.where(id: [1,2,3,4,1234]).pluck(:id)
  SQL (2.5ms)  SELECT `users`.`id` FROM `users` WHERE `users`.`id` IN (1, 2, 3, 4, 1234)
 => [1, 2, 3] 

请注意:

建议(现已删除)Model.find([2, 3, 1])等效的,如果数组中的任何 id 不存在,它将抛出异常。

同样,建议(现已删除)Model.find_by(id: [2, 3, 1])等效,它只返回一个结果。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-08-08
    • 2010-10-03
    • 1970-01-01
    • 2011-08-29
    • 1970-01-01
    • 2020-05-16
    • 2021-11-02
    • 2020-12-02
    相关资源
    最近更新 更多