How to exclude an array of ids from query in Rails (using ActiveRecord)?

前端 未结 4 706
陌清茗
陌清茗 2020-12-13 07:13

I would like to perform an ActiveRecord query that returns all records except those records that have certain ids. The ids I would like excluded are stored in an array. So

4条回答
  •  心在旅途
    2020-12-13 07:22

    As nslocum wrote, the following works well:

    Item.where.not(id: ids_to_exclude)
    

    If your "ids to exclude" come from a query (here with an example condition), you can even take it a step further:

    Item.where.not(id: Item.where(condition: true))
    

    This is useful if you need to filter another model:

    OtherModel.where.not(item_id: Item.where(condition: true))
    

提交回复
热议问题