1
0
Fork 0
mirror of https://github.com/rails/rails.git synced 2022-11-09 12:12:34 -05:00

Merge pull request #39501 from kamipo/alias_attribute_for_validation

Allow attribute aliases for `validates_uniqueness_of`
This commit is contained in:
Ryuta Kamizono 2020-06-02 21:16:42 +09:00 committed by GitHub
commit 8504576bcf
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 23 additions and 1 deletions

View file

@ -78,7 +78,7 @@ module ActiveRecord
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

View file

@ -156,6 +156,25 @@ class UniquenessValidationTest < ActiveRecord::TestCase
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 })

View file

@ -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