MySQL Rails 控制台通过 id 数组查找用户

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21435768/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 19:55:24  来源:igfitidea点击:

Rails Console find users by array of ids

mysqlruby-on-railsrubypostgresqlrails-console

提问by Seth

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

所以我有一组用户ID。有没有办法在 rails 控制台中使用数组查询所有这些用户

something like

就像是

ids = [1, 2, 3, 4]

users = User.find(ids)

and have it return all 4 users?

并返回所有 4 个用户?

回答by Grant Birchmeier

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

As @diego.greyrobot notes in a comment, a range causes a SQL BETWEEN clause, whereas an array causes a SQL IN clause.

正如@diego.greyrobot 在评论中指出的那样,范围导致 SQL BETWEEN 子句,而数组导致 SQL IN 子句。

Don'tuse User.find_by_id()-- It will only return one record, no matter how may IDs you pass in.

不要使用User.find_by_id()——它只会返回一条记录,不管你传入的 ID 是多少。

回答by Nitin Jain

you can use User.where(id: ids)

您可以使用 User.where(id: ids)

回答by BroiSatse

Use splash operator:

使用飞溅运算符:

ids = [1, 2, 3, 4]

users = User.find(*ids)

Note that it will raise an exception if it fails to find any of the users.

请注意,如果找不到任何用户,它将引发异常。

回答by Dheer

This is work for me...

这对我来说是工作......

ids = [1, 2, 3, 4]

users = User.find(ids)

users = User.find(*ids)

users = User.find_all_by_id(ids)

All are working..

都在工作..

回答by Tarek Saied

you can use

您可以使用

   Users.where({ id: [1,2,3 ,4]})
 # SELECT * FROM users WHERE id IN (1,2,3,4)

回答by Abdo

What you're doing is supposed to work when all the ids exist.

当所有 id 都存在时,你正在做的事情应该可以工作。

The reason you might be seeing an exception is because at least one of those ids does not exist in the database.

您可能会看到异常的原因是数据库中至少不存在这些 ID 之一。

Instead, you want to use find_all_by_idif you don't want to get an exception:

相反,find_all_by_id如果你不想得到异常,你想使用:

User.find_all_by_id([1, 2, 3, 4])

# Does the following sql:    
User Load (0.4ms)  SELECT `users`.* FROM `users` WHERE `users`.`id` IN (1, 2, 3, 4)