Set*_*eth 43 ruby mysql postgresql ruby-on-rails rails-console
所以我有一组用户ID.在rails控制台中是否有一种方法可以使用该数组查询所有这些用户
就像是
ids = [1, 2, 3, 4]
users = User.find(ids)
Run Code Online (Sandbox Code Playgroud)
并让它返回所有4个用户?
Gra*_*ier 108
对于数组,您可以使用以下方法之一:
# 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
Run Code Online (Sandbox Code Playgroud)
如果您恰好使用范围,可以使用以下方法:
# 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
Run Code Online (Sandbox Code Playgroud)
正如@ diego.greyrobot在注释中所指出的,范围会导致SQL BETWEEN子句,而数组会导致SQL IN子句.
不要使用User.find_by_id()- 它只会返回一条记录,无论你传入的ID如何.
| 归档时间: |
|
| 查看次数: |
54838 次 |
| 最近记录: |