Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails - how to subtract one query from another?

I want to do something like this:

puts Room.find(1,2,3) - Room.find(1,2)

so that it does Room.find(3) and returns that SQL record only instead of the 3 records that Room.find(1,2,3) gives me

like image 653
junky Avatar asked Jan 14 '23 15:01

junky


2 Answers

I think this will be much more efficient:

first_id_list = [1, 2, 3]
second_id_list = [1, 2]
Room.find(first_id_list - second_id_list)

That way, you only search for the id's that you really want to be in your query, instead of fetching unwanted rows and then instantiating a bunch of Room objects that you then promptly ignore but Ruby still has to garbage collect.

like image 174
sockmonk Avatar answered Jan 19 '23 10:01

sockmonk


As Anthony Alberto pointed out in the comment. This works. Only case this won't work is when you find just one instance of room. For example Room.find(1) will return an object of class Room, rather than an Array. Therefore you won't be able to use the binary operator - on this Speak object. To avoid this from happening, use to_a method.

Array.wrap(Room.find(1,2,3)) - Array.wrap(Room.find(1))
=> Room.find(2,3)
like image 30
Jason Kim Avatar answered Jan 19 '23 11:01

Jason Kim