Last Updated: February 25, 2016
· 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

class Person < ActiveRecord::Base
    has_and_belongs_to_many :rooms

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

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.