Rails Console通过ID数组查找用户 [英] Rails Console find users by array of ids
本文介绍了Rails Console通过ID数组查找用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
所以我有一个用户ID数组. Rails控制台中是否可以通过数组查询所有这些用户
So I have an array of user ids. Is there a way in rails console to query all of these user's with the array
类似
ids = [1, 2, 3, 4]
users = User.find(ids)
它返回了所有4个用户吗?
and have it return all 4 users?
推荐答案
对于数组,可以使用以下之一:
For an array, you can use one of these:
# Will raise exception if any value not found
User.find( [1,3,5] )
# Will not raise an exception
User.find_all_by_id( [1,3,5] ) # Rails 3
User.where(id: [1,3,5]) # Rails 4
如果您恰好在使用范围,则可以使用以下内容:
If you happen to be using a range, you can use these:
# Will raise exception if any value not found
User.find((1..4).to_a) #same as User.find([1,2,3,4])
# Will not raise an exception
User.find_all_by_id(1..4) # Rails 3
User.where(id: 1..4) # Rails 4
正如@ diego.greyrobot在注释中指出的,范围导致SQL BETWEEN子句,而数组导致SQL IN子句.
As @diego.greyrobot notes in a comment, a range causes a SQL BETWEEN clause, whereas an array causes a SQL IN clause.
不要使用User.find_by_id()
-无论您传递多少ID,它都只会返回一条记录.
Don't use User.find_by_id()
-- It will only return one record, no matter how may IDs you pass in.
这篇关于Rails Console通过ID数组查找用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文