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

前端 未结 4 681
陌清茗
陌清茗 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))
    
    0 讨论(0)
  • 2020-12-13 07:29

    This should work:

    ids_to_exclude = [1,2,3]
    items_table = Arel::Table.new(:items)
    
    array_without_excluded_ids = Item.where(items_table[:id].not_in ids_to_exclude)
    

    And it's fully object-oriented with no strings :-)

    0 讨论(0)
  • 2020-12-13 07:37

    Rails 4 solution:

    ids_to_exclude = [1,2,3]
    array_without_excluded_ids = Item.where.not(id: ids_to_exclude)
    
    0 讨论(0)
  • 2020-12-13 07:39

    You can also use Squeel gem to accomplish such query. Documentation of it, goes here

    0 讨论(0)
提交回复
热议问题