Say I have two relations that hold records in the same model, such as:
@companies1 = Company.where(...) @companies2 = Company.where(...)
Ho
Use sql keyword INTERSECT.
params1 = [1,2,4] params2 = [1,3,4] query = " SELECT companies.* FROM companies WHERE id in (?,?,?) INTERSECT SELECT companies.* FROM companies WHERE id in (?,?,?) " Company.find_by_sql([query, *params1, *params2])
it will be faster than previous solution.