Merge pull request #18932 from mcmire/ew-uniqueness-array-scopes

Scopes can be array columns for uniq. validator
This commit is contained in:
Sean Griffin 2015-02-13 15:42:59 -07:00
commit ce20853aff
3 changed files with 23 additions and 2 deletions

View File

@ -81,7 +81,13 @@ module ActiveRecord
else
scope_value = record.read_attribute(scope_item)
end
relation = relation.and(table[scope_item].eq(scope_value))
# This is basically emulating an Arel::Nodes::Casted
column = record.class.columns_hash[scope_item.to_s]
quoted_value = record.class.connection.quote(scope_value, column)
node = Arel::Nodes::SqlLiteral.new(quoted_value)
relation = relation.and(table[scope_item].eq(node))
end
relation

View File

@ -45,6 +45,11 @@ class UniquenessValidationTest < ActiveRecord::TestCase
repair_validations(Topic, Reply)
class ModelWithScopedValidationOnArray < ActiveRecord::Base
self.table_name = 'postgresql_arrays'
validates_uniqueness_of :name, scope: [:commission_by_quarter]
end
def test_validate_uniqueness
Topic.validates_uniqueness_of(:title)
@ -388,6 +393,15 @@ class UniquenessValidationTest < ActiveRecord::TestCase
assert e2.errors[:nicknames].any?, "Should have errors for nicknames"
assert_equal ["has already been taken"], e2.errors[:nicknames], "Should have uniqueness message for nicknames"
end
def test_validate_uniqueness_scoped_to_array
record = ModelWithScopedValidationOnArray.new(
name: "Sheldon Cooper",
commission_by_quarter: [1, 2, 3]
)
assert_nothing_raised { record.valid? }
end
end
def test_validate_uniqueness_on_existing_relation

View File

@ -62,7 +62,8 @@ _SQL
CREATE TABLE postgresql_arrays (
id SERIAL PRIMARY KEY,
commission_by_quarter INTEGER[],
nicknames TEXT[]
nicknames TEXT[],
name TEXT
);
_SQL