fix the uniqueness validation scope with a polymorphic association

https://gist.github.com/sergey-alekseev/946657ebdb5e58d1bee115714056ec96
This commit is contained in:
Sergey Alekseev 2016-11-26 15:17:11 +03:00
parent ebdf87a0bd
commit 8a0fda63aa
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 @@ def build_relation(klass, attribute, value) # :nodoc:
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/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 @@ def test_validate_uniqueness_with_object_scope
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"