Rails Console find users by array of ids

前端 未结 6 1488
清歌不尽
清歌不尽 2020-12-23 19:25

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

something like

ids = [1, 2, 3, 4]

users         


        
6条回答
  •  情深已故
    2020-12-23 19:42

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

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

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

    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)
    

提交回复
热议问题