所以我有一个用户 ID 数组。 Rails 控制台中是否有办法使用数组查询所有这些用户
类似
ids = [1, 2, 3, 4]
users = User.find(ids)
让它返回所有 4 个用户?
最佳答案
对于数组,您可以使用以下之一:
# 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
如果你碰巧使用了一个范围,你可以使用这些:
# 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 子句。
不要使用User.find_by_id()
——不管你传入多少ID,它只会返回一条记录。
https://stackoverflow.com/questions/21435768/