None of the previous answers is accurate. If you need to get records that have all specified values, but not only some of the values, you don't need to use WHERE n_code IN (2,3,5) condition, because it will get all records that have at least one of the values, but not all of them at the same time. Also, additional condition HAVING count(codes.n_code) = 3, as suggested earlier, is not a solution, as it does not guarantee that these 3 values are actually 2, 3 and 5.
I am not good at Ruby, so I will give you an example in plain SQL how you can get records that have all of the values:
SELECT company_codes.company_id
FROM company_codes
JOIN codes ON codes.id = company_codes.code_id
GROUP BY company_codes.company_id
HAVING array_agg(codes.n_code) @> ARRAY[2, 3, 5]
How it works: in HAVING section you aggregate all n_code values for a company into an array (note that the query is grouped by a company) and check that it contains the array on the right (contains all of its values).
codestable three times. Please, correct me if I am wrong..joinbecause of rails associations rails is smart enough to automatically to perform the join on company codes and then codes for you.array_aggto gel a list of codes for every company and then filter for arrays that contain[2,3,5]