rails icon indicating copy to clipboard operation
rails copied to clipboard

[AR] Fix uniqueness validation on association not using overridden PK

Open mikeletscher opened this issue 1 year ago • 2 comments

Summary

Resolves #45775

Fixes what I believe is a bug where a uniqueness validation on a belongs_to association was not using the correct value in the query for existing records. The ID of the associated model was being used instead of the overridden primary_key column value.

Other Information

From some quick grepping, it doesn't look like this bind_attribute method is used anywhere other this uniqueness validation.

mikeletscher avatar Aug 08 '22 18:08 mikeletscher

As I commented at https://github.com/rails/rails/issues/45775#issuecomment-1209230585 , the original issue is due to missing/incorrect self.primary_key at the referenced model.

yahonda avatar Aug 09 '22 11:08 yahonda

@yahonda I left a comment on the issue, but following up here. It appears to me that ActiveRecord already supports this use case—there's an existing test model and test using the primary_key options for an association to a model that doesn't have primary_key defined using self.primary_key=. The PR was to address that the uniqueness validation doesn't seem to also support this behavior.

mikeletscher avatar Sep 19 '22 14:09 mikeletscher

After thinking about this pull request for some time, I have decided to merge this pull request. Thanks for the contribution.

yahonda avatar Sep 28 '22 08:09 yahonda

Created a backport for 7-0-stable - https://github.com/rails/rails/pull/49300.

fatkodima avatar Sep 16 '23 09:09 fatkodima