nexar
nexar

Reputation: 11336

How to remove items from Activerecord query resultset?

I get a resultset from a Rails find query. I want to iterate over that resultset and depending on certain criteria drop records from that resultset before passing it on for further processing. The additional criteria are external to the data held in the database and hence I can't include them in the original 'find' query.

Note I don't want to delete any records from the database just remove them from the resultset.

Please can someone give me the code to do that.

Upvotes: 31

Views: 18931

Answers (4)

Epigene
Epigene

Reputation: 3928

If some processing must be done in application code that SQL can not do, and the result must be a changed query object, re-querying the objects by id might be a (very memory inefficient) option.

needed_ids = Model.where(<some original query>).map{|r| r.something? ? r.id : nil }.compact
new_collection = Model.where(id: needed_ids)

Upvotes: 2

Fabio
Fabio

Reputation: 19216

Use reject as in

Model.find_all_by_xxx().reject { |r| r.something? }

Upvotes: 32

Marcus S&#225;
Marcus S&#225;

Reputation: 608

You can use delete_at too:

irb(main):005:0> c = Category.all
Category Load (0.3ms)  SELECT "categories".* FROM "categories" 
=> [#<Category id: 1, name: "15 anos", description: nil, created_at: "2011-09-22 04:52:53", updated_at: "2011-09-22 04:52:53">]
irb(main):006:0> c.delete_at(0)
=> #<Category id: 1, name: "15 anos", description: nil, created_at: "2011-09-22 04:52:53", updated_at: "2011-09-22 04:52:53">
irb(main):007:0> c
=> []

Upvotes: -1

fl00r
fl00r

Reputation: 83680

set = MyObject.find(...)
set = set.reject{|s| ... }

or

set = set.select{|s| ... }

Upvotes: 6

Related Questions