I've got a simple scenario, but I can't seem to find any proposed solutions that apply to Rails 4. I want to simply add a custom validator that checks the amount of stored associations between my HABTM association. Easier said and done, to my surprise?
I've searched for a solution but only end up with answers for older versions of Rails it seems. I've got the following:
class User < ActiveRecord::Base
has_and_belongs_to_many :roles
after_save :check_maximum_number_of_roles
.
.
.
private
def check_maximum_number_of_roles
if self.roles.length > 3
errors.add(:roles, 'Users can only have three roles assigned.')
return false
end
end
end
class Role < ActiveRecord::Base
has_and_belongs_to_many :users
end
The reason I use after_save
is because as far as I understand the stored association is first available after it has been added. I've also tried to write an custom validator (e.g. validate: :can_only_have_one_role
), but that does not work either.
I add the association in the following manner and have done this in the rails console (which should work just fine?):
user.roles << role
Nevertheless, it adds more than one role to users and does not care of any type of validation.
Help much appreciated, thanks!
has_many/belongs_to
pairing instead of ahas_and_belongs_to_many
... – Chemoprophylaxishas_and_belongs_to_many
and see my answer below. – Chemoprophylaxis