How to select where ID in Array Rails ActiveRecord without exception

前端 未结 6 809
余生分开走
余生分开走 2020-12-07 16:13

When I have array of ids, like

ids = [2,3,5]

and I perform

Comment.find(ids)

everything works fine. But w

6条回答
  •  一个人的身影
    2020-12-07 17:00

    If it is just avoiding the exception you are worried about, the "find_all_by.." family of functions works without throwing exceptions.

    Comment.find_all_by_id([2, 3, 5])
    

    will work even if some of the ids don't exist. This works in the

    user.comments.find_all_by_id(potentially_nonexistent_ids)
    

    case as well.

    Update: Rails 4

    Comment.where(id: [2, 3, 5])
    

提交回复
热议问题