How to select where ID in Array Rails ActiveRecord without exception

前端 未结 6 799
余生分开走
余生分开走 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 16:54

    Now .find and .find_by_id methods are deprecated in rails 4. So instead we can use below:

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

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

    user.comments.where(id: avoided_ids_array)
    

    Also for excluding ID's

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

提交回复
热议问题