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:
commit
8504576bcf
3 changed files with 23 additions and 1 deletions
|
@ -78,7 +78,7 @@ module ActiveRecord
|
||||||
scope_value = if record.class._reflect_on_association(scope_item)
|
scope_value = if record.class._reflect_on_association(scope_item)
|
||||||
record.association(scope_item).reader
|
record.association(scope_item).reader
|
||||||
else
|
else
|
||||||
record._read_attribute(scope_item)
|
record.read_attribute(scope_item)
|
||||||
end
|
end
|
||||||
relation = relation.where(scope_item => scope_value)
|
relation = relation.where(scope_item => scope_value)
|
||||||
end
|
end
|
||||||
|
|
|
@ -156,6 +156,25 @@ class UniquenessValidationTest < ActiveRecord::TestCase
|
||||||
assert r3.valid?, "Saving r3"
|
assert r3.valid?, "Saving r3"
|
||||||
end
|
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
|
def test_validate_uniqueness_with_scope_invalid_syntax
|
||||||
error = assert_raises(ArgumentError) do
|
error = assert_raises(ArgumentError) do
|
||||||
Reply.validates_uniqueness_of(:content, scope: { parent_id: false })
|
Reply.validates_uniqueness_of(:content, scope: { parent_id: false })
|
||||||
|
|
|
@ -10,6 +10,9 @@ class Reply < Topic
|
||||||
|
|
||||||
scope :ordered, -> { Reply.order(:id) }
|
scope :ordered, -> { Reply.order(:id) }
|
||||||
|
|
||||||
|
alias_attribute :new_content, :content
|
||||||
|
alias_attribute :new_parent_id, :parent_id
|
||||||
|
|
||||||
# Method on Kernel
|
# Method on Kernel
|
||||||
def self.open
|
def self.open
|
||||||
approved
|
approved
|
||||||
|
|
Loading…
Reference in a new issue