I get a resultset from a Rails find query. I want to iterat开发者_如何学Ce 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.
Use reject as in
Model.find_all_by_xxx().reject { |r| r.something? }
set = MyObject.find(...)
set = set.reject{|s| ... }
or
set = set.select{|s| ... }
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)
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
=> []
精彩评论