How to select where ID in Array Rails ActiveRecord without exception

前端 未结 6 801
余生分开走
余生分开走 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条回答
  •  Happy的楠姐
    2020-12-07 16:47

    Update: This answer is more relevant for Rails 4.x

    Do this:

    current_user.comments.where(:id=>[123,"456","Michael Jackson"])
    

    The stronger side of this approach is that it returns a Relation object, to which you can join more .where clauses, .limit clauses, etc., which is very helpful. It also allows non-existent IDs without throwing exceptions.

    The newer Ruby syntax would be:

    current_user.comments.where(id: [123, "456", "Michael Jackson"])
    

提交回复
热议问题