mirror of
https://github.com/rails/rails.git
synced 2022-11-09 12:12:34 -05:00
Merge pull request #26865 from sergey-alekseev/uniqueness-validation-scope-with-polymorphic-association
fix the uniqueness validation scope with a polymorphic association
This commit is contained in:
commit
747ddd34ab
3 changed files with 23 additions and 4 deletions
|
@ -1,3 +1,7 @@
|
|||
* Fix the uniqueness validation scope with a polymorphic association.
|
||||
|
||||
*Sergey Alekseev*
|
||||
|
||||
* Raise ActiveRecord::RecordNotFound from collection `*_ids` setters
|
||||
for unknown IDs with a better error message.
|
||||
|
||||
|
|
|
@ -85,11 +85,10 @@ module ActiveRecord
|
|||
|
||||
def scope_relation(record, relation)
|
||||
Array(options[:scope]).each do |scope_item|
|
||||
if reflection = record.class._reflect_on_association(scope_item)
|
||||
scope_value = record.send(reflection.foreign_key)
|
||||
scope_item = reflection.foreign_key
|
||||
scope_value = if record.class._reflect_on_association(scope_item)
|
||||
record.association(scope_item).reader
|
||||
else
|
||||
scope_value = record._read_attribute(scope_item)
|
||||
record._read_attribute(scope_item)
|
||||
end
|
||||
relation = relation.where(scope_item => scope_value)
|
||||
end
|
||||
|
|
|
@ -6,6 +6,9 @@ require "models/guid"
|
|||
require "models/event"
|
||||
require "models/dashboard"
|
||||
require "models/uuid_item"
|
||||
require "models/author"
|
||||
require "models/person"
|
||||
require "models/essay"
|
||||
|
||||
class Wizard < ActiveRecord::Base
|
||||
self.abstract_class = true
|
||||
|
@ -163,6 +166,19 @@ class UniquenessValidationTest < ActiveRecord::TestCase
|
|||
assert !r2.valid?, "Saving r2 first time"
|
||||
end
|
||||
|
||||
def test_validate_uniqueness_with_polymorphic_object_scope
|
||||
Essay.validates_uniqueness_of(:name, scope: :writer)
|
||||
|
||||
a = Author.create(name: "Sergey")
|
||||
p = Person.create(first_name: "Sergey")
|
||||
|
||||
e1 = a.essays.create(name: "Essay")
|
||||
assert e1.valid?, "Saving e1"
|
||||
|
||||
e2 = p.essays.create(name: "Essay")
|
||||
assert e2.valid?, "Saving e2"
|
||||
end
|
||||
|
||||
def test_validate_uniqueness_with_composed_attribute_scope
|
||||
r1 = ReplyWithTitleObject.create "title" => "r1", "content" => "hello world"
|
||||
assert r1.valid?, "Saving r1"
|
||||
|
|
Loading…
Reference in a new issue