Rails Daily: Composite Foreign Key Validation Fix
Felix-d fixed a validation condition bug for belongs_to associations with composite foreign keys in ActiveRecord. The fix ensures proper validation behavior when belongs_to_required_validates_foreign_key is disabled.
Duration: PT1M52S
Transcript
Good morning, this is Rails Daily for April 4th, 2026.
Felix-d merged a fix for belongs_to validation condition handling with composite foreign keys. The issue occurred when `belongs_to_required_validates_foreign_key` is set to false, which has been the default since Rails 7.1. In this configuration, Rails uses a conditional presence validator that checks if foreign keys are nil or have changed before running validation.
The problem was that the existing validation condition only worked with single foreign keys. For composite foreign keys - where an association uses multiple columns - the condition would fail because it expected a single value rather than an array of values. This could lead to validation running incorrectly or not at all for models using composite primary keys.
The fix updates the condition lambda in the belongs_to association builder to properly handle both single and composite foreign key scenarios. The change adds logic to check if the foreign key is an array and validates each component appropriately. Felix-d included comprehensive tests covering the composite foreign key validation scenarios, adding test coverage to the belongs_to associations test suite and creating a new composite primary key book model for testing.
The pull request received one approval and minimal discussion, indicating this was a straightforward bug fix. The changes touch three files with 39 additions and 2 deletions, keeping the implementation focused and minimal.
What's next: This fix will be particularly valuable for applications migrating to composite primary keys, a feature that's becoming more important as Rails applications scale. Developers using composite foreign keys should see more reliable validation behavior in their belongs_to associations.
That's your Rails update for today. We'll be back tomorrow with more Rails core developments.