Skip to content

Commit

Permalink
Merge pull request #39501 from kamipo/alias_attribute_for_validation
Browse files Browse the repository at this point in the history
Allow attribute aliases for `validates_uniqueness_of`
  • Loading branch information
kamipo committed Jun 2, 2020
2 parents da05122 + 7ae406a commit 8504576
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 1 deletion.
2 changes: 1 addition & 1 deletion activerecord/lib/active_record/validations/uniqueness.rb
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ def scope_relation(record, relation)
scope_value = if record.class._reflect_on_association(scope_item)
record.association(scope_item).reader
else
record._read_attribute(scope_item)
record.read_attribute(scope_item)
end
relation = relation.where(scope_item => scope_value)
end
Expand Down
19 changes: 19 additions & 0 deletions activerecord/test/cases/validations/uniqueness_validation_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,25 @@ def test_validate_uniqueness_with_scope
assert r3.valid?, "Saving r3"
end

def test_validate_uniqueness_with_aliases
Reply.validates_uniqueness_of(:new_content, scope: :new_parent_id)

t = Topic.create(title: "I'm unique!")

r1 = t.replies.create(title: "r1", content: "hello world")
assert_predicate r1, :valid?, "Saving r1"

r2 = t.replies.create(title: "r2", content: "hello world")
assert_not_predicate r2, :valid?, "Saving r2 first time"

r2.content = "something else"
assert r2.save, "Saving r2 second time"

t2 = Topic.create("title" => "I'm unique too!")
r3 = t2.replies.create(title: "r3", content: "hello world")
assert_predicate r3, :valid?, "Saving r3"
end

def test_validate_uniqueness_with_scope_invalid_syntax
error = assert_raises(ArgumentError) do
Reply.validates_uniqueness_of(:content, scope: { parent_id: false })
Expand Down
3 changes: 3 additions & 0 deletions activerecord/test/models/reply.rb
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@ class Reply < Topic

scope :ordered, -> { Reply.order(:id) }

alias_attribute :new_content, :content
alias_attribute :new_parent_id, :parent_id

# Method on Kernel
def self.open
approved
Expand Down

0 comments on commit 8504576

Please sign in to comment.