Search code examples
ruby-on-railsvalidationsingle-table-inheritance

rails validate uniqueness within inheritance


I have to models: Tag and TagNumeric each one with a category field

I shouldn't be able to create Tags of different types with the same category. How can I validate this?

EDIT:

I forgot to mention

TagNumeric < Tag

class Tag
 include Mongoid::Document

 validates_presence_of :type, :value

 field :category, type: String
 field :value, type: String
 field :color, type: String
 validates :value, :presence => true, :uniqueness => {:scope => :category}



class TagNumeric < Tag

  field :value, type: Integer

it 'its category should be unique within the Tag class type' do
  Tag.create(category: 'Movie', value: 'Avatar')
  TagNumeric.create(category: 'Movie', value: 'Iron man').should_not be_valid
end

Solution

  • If anybody is having the same problem here is how I solved it

    validate :uniqueness_within_category
    def uniqueness_within_category
      first_category_type = (Tag.find_by(category: self.category).nil?)? 'none' : Tag.find_by(category: self.category)._type
      if first_category_type == 'none'
        #It doesnt exist then should be allowed
        return
      end
      #If it exists within another class type then shouldnt be allowed
      if self._type != first_category_type
        errors.add(:category, 'Must be unique within tag type')
      end
    end
    

    Testing started at 6:22 PM ...

    1 examples, 0 failures, 1 passed