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
endIf 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
endThe 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.
Written by Fernando Doglio
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
 #Rails 
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#

 
 
 
 
