Search code examples
mongoidmongoid3

Mongoid unique model references


I'm using Mongoid 3. I have a simple class Tour and references multiple Itineraries. Is there a way that I can validate that for each tour, the itineraries' dates are unique, i.e. I can't have 2 itineraries of the same date for a single tour.

class Tour
  has_many :itineraries
end

class Itinerary
  field :date, :type => Date
  validates :date, :presence => true
  index({date: 1})

  belongs_to :tour
end

I'm not sure how to set up the validation.


Solution

  • You can create custom validations :

    class Tour
      has_many :itineraries
      validates :check_uniqueness_of_date # This line
    
      # And this part
      private 
      def check_uniqueness_of_date
        # Check validation here
      end
    end
    

    Another Stackoverflow Question

    Rails Guides