'Nulls handled differently for ActiveRecord has_many with custom primary_key after upgrade to Rails 5

I'm working on a bug caused by a change in behavior after an upgrade from Rails 4 -> Rails 5.

On a model, we have a has_many association declared thusly:

has_many :things, foreign_key: :special_id, primary_key: :special_id

The problem occurs when the special_id field is nil on the parent model. In Rails 4 that scenario produces the following query:

SELECT * FROM "things" WHERE "things"."special_id" = $1  [["special_id", nil]]

which returns zero records. (ie doesn't match on NULL foreign keys)

In Rails 5, the query changes to:

SELECT * FROM "things" WHERE "things"."special_id" IS NULL

which returns every record from the things table with a NULL special_id. (ie does match on NULL foreign keys)

The existing model's callbacks expect a model with a NULL special_id to have zero :things associated with it. Is there an option, or alternative way to construct this association, that will omit the child records with NULL in the foreign_key field?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source