Skip to content

Commit 441f967

Browse files
authored
Merge pull request rails#45790 from mikeletscher/bind-attribute-primary-key-relation
[AR] Fix uniqueness validation on association not using overridden PK
2 parents 2fb72f5 + 3c8dab7 commit 441f967

File tree

2 files changed

+19
-1
lines changed

2 files changed

+19
-1
lines changed

activerecord/lib/active_record/relation.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ def initialize_copy(other)
4545
def bind_attribute(name, value) # :nodoc:
4646
if reflection = klass._reflect_on_association(name)
4747
name = reflection.foreign_key
48-
value = value.read_attribute(reflection.klass.primary_key) unless value.nil?
48+
value = value.read_attribute(reflection.association_primary_key) unless value.nil?
4949
end
5050

5151
attr = table[name]

activerecord/test/cases/validations/uniqueness_validation_test.rb

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
require "models/author"
1212
require "models/person"
1313
require "models/essay"
14+
require "models/keyboard"
1415

1516
class Wizard < ActiveRecord::Base
1617
self.abstract_class = true
@@ -70,6 +71,14 @@ def set_author
7071
end
7172
end
7273

74+
class LessonWithUniqKeyboard < ActiveRecord::Base
75+
self.table_name = "lessons"
76+
77+
belongs_to :keyboard, primary_key: :name, foreign_key: :name
78+
79+
validates_uniqueness_of :keyboard
80+
end
81+
7382
class UniquenessValidationTest < ActiveRecord::TestCase
7483
INT_MAX_VALUE = 2147483647
7584

@@ -766,6 +775,15 @@ def test_uniqueness_on_relation
766775
Event.delete_all
767776
end
768777

778+
def test_uniqueness_on_custom_relation_primary_key
779+
Keyboard.create!(name: "Keyboard #1")
780+
LessonWithUniqKeyboard.create!(name: "Keyboard #1")
781+
782+
another = LessonWithUniqKeyboard.new(name: "Keyboard #1")
783+
assert_not_predicate another, :valid?
784+
assert_equal ["has already been taken"], another.errors[:keyboard]
785+
end
786+
769787
def test_index_of_sublist_of_columns
770788
Topic.validates_uniqueness_of(:title, scope: :author_name)
771789
@connection.add_index(:topics, :author_name, unique: true, name: :topics_index)

0 commit comments

Comments
 (0)