Last Updated: February 25, 2016
·
2.774K
· deleteman

Validating uniqueness on HABTM associations

When tyring to validate uniqueness on a hasandbelongstomany there is a nice little callback that you can use to manually check for that:

Lets use an example:

class Room < ActiveRecord::Base
    has_and_belongs_to_many :people
end

class Person < ActiveRecord::Base
    has_and_belongs_to_many :rooms
end

If we wanted to make sure that a room can't have more than 5 people inside it, we can do:

class Room < ActiveRecord::Base
   has_and_belongs_to_many :people, before_add: :check_people_inside

   def check_people_inside person
      raise ActiveRecord::Rollback if people.count == 5
   end
end

The rollback will be caught automatically for you and the new record won't be added to the relation.
You can customize the validator, to add error messages, to use on forms and the like.