Skip to content

Commit

Permalink
Refactor validates_uniqueness_to_tenant
Browse files Browse the repository at this point in the history
  • Loading branch information
artplan1 committed Dec 10, 2020
1 parent b72dfba commit 47d6f24
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 20 deletions.
26 changes: 7 additions & 19 deletions lib/acts_as_tenant/model_extensions.rb
Original file line number Diff line number Diff line change
Expand Up @@ -93,34 +93,22 @@ def scoped_by_tenant?

def validates_uniqueness_to_tenant(fields, args = {})
raise ActsAsTenant::Errors::ModelNotScopedByTenant unless respond_to?(:scoped_by_tenant?)

fkey = reflect_on_association(ActsAsTenant.tenant_klass).foreign_key
# tenant_id = lambda { "#{ActsAsTenant.fkey}"}.call
args[:scope] = if args[:scope]

validation_args = args.clone
validation_args[:scope] = if args[:scope]
Array(args[:scope]) << fkey
else
fkey
end

validates_uniqueness_of(fields, args)
validates_uniqueness_of(fields, validation_args)

if ActsAsTenant.models_with_global_records.include?(self)
validate do |instance|
Array(fields).each do |field|
if instance.new_record?
unless self.class.where(fkey.to_sym => [nil, instance[fkey]],
field.to_sym => instance[field]).empty?
errors.add(field, "has already been taken")
end
else
unless self.class.where(fkey.to_sym => [nil, instance[fkey]],
field.to_sym => instance[field])
.where.not(id: instance.id).empty?
errors.add(field, "has already been taken")
end
global_validation_args = args.merge(conditions: -> { where(fkey => nil) })

end
end
end
validates_uniqueness_of(fields, global_validation_args)
end
end
end
Expand Down
2 changes: 1 addition & 1 deletion spec/models/model_extensions_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@
expect(GlobalProject.new(name: "foo new").valid?).to be(true)
end

it "is invalid with with duplicate tenant records" do
it "is invalid with duplicate tenant records" do
expect(GlobalProject.new(name: "global foo").valid?).to be(false)
end

Expand Down

0 comments on commit 47d6f24

Please sign in to comment.