Rails nested form - validate uniqueness - combination of child objects
===

I have the following model:

    class TemplateMap < ActiveRecord::Base
      attr_accessible :template_id, :unit_ids
  
      has_many :unit_template_maps
      has_many :units, :through => :unit_template_maps
  
      accepts_nested_attributes_for :units

The idea is to allow you to create combinations of units and map them to a single template id. I want to add validation to only allow unique combinations of units. 

I'm accomplishing this today using the following code:

      validate :unique_units_combination
  
      private
  
      def unique_units_combination
        n = 0
        TemplateMap.all.each do |t|
          n += 1 if t.units == units
        end
        errors.add(:template_id, "combination already exists") if n > 0
      end

can anyone recommend a better way to do this?