Merge does not handle multiple in clauses

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the rails category.

Last Updated: 2024-11-23

The following code generates an in clause for the taxonomy bit:

subject_taxons = Taxon.where(taxonomy: Taxonomy.overall_subject)

Here is the SQL generated:

SELECT taxons.* FROM taxons 
WHERE taxons.taxonomy_id IN (SELECT
  taxonomies.id FROM taxonomies WHERE taxonomies.name = 'Subject'
 )

I merged in another SQL IN clause to the scope above, expecting that the results would be filtered to taxons that were members of both taxonomies.

institution_taxons =  Taxon.where(taxonomy: Taxonomy.institution)
subject_taxons.merge(institution_taxons)

This gave the following SQL

SELECT taxons.* FROM taxons 
WHERE taxons.taxonomy_id IN (SELECT
  taxonomies.id FROM taxonomies WHERE taxonomies.name = 'Subject'
 )

I.e. what happened was that the last/final SQL in clause had overwritten the first one in the sequence of merges.

This is probably a difficult problem to solve, in that it is vague whether I meant either to grab taxons - both in the subject AND institution taxonomies - either in the subject OR institution taxonomies

Lessons

ActiveRecord#merge does not handle multiple SQL IN () clauses.