0

I am running 2 (sometimes 3) searches, like:

first_search  = Company.where('...') # returns 2 objects
second_search = Company.where('...') # returns 4 objects

Let's say that first_search contains objects with these IDs:

10
20

second_search contains

10
30
40
50

I would like to save to another variable (say results) objects with the same IDs from first_search and second_search, thus results would only contain the object with ID:

10

How to do this?

Thank you/

EDIT: the intersection is working based on the id column, right? Would be there a way to make the intersection work on a different column? Say name?

user984621
  • 46,344
  • 73
  • 224
  • 412

2 Answers2

1

Looks like this works on objects as well.

results = first_search & second_search
Nithin
  • 3,679
  • 3
  • 30
  • 55
  • Thank you @Nithin for the answer - this intersection works based on the `id` column, right? Would be there a way to make the intersection work on a different column? Say `name`? Thank you – user984621 Feb 22 '16 at 05:26
1

You are just trying to take intersection, you can do

results = first_search & second_search

but as you want to find intersection of objects, here is the link that already answers it. I hope it helps you.

Intersection of two relations

Community
  • 1
  • 1
kamal
  • 996
  • 15
  • 25