I have a user model with a HABTM relationship to groups. I do not want a user to be able to be in more than 5 groups, so would like to validate the length of the HABTM relationship.
On the edit user page I have a list of checkboxes where the user can select the groups they want to be in (I'm using formtastic for the form).
In my users controller I'm calling:
@user.update_attributes(params[:user])
which is causing rails to update the associations automatically.
In my user model I have the following:
def validate
if self.groups.length > 5
self.errors.add(:groups, "cannot have more than 5 groups")
end
end
This is causing the form to fail the validation, but the update_attributes call has already updated the database to reflect the changes to the associated groups. This way every time a user clicks the save button their group associations are saved, even though the record is invalid.
What's the best way to solve this?
I think perhaps the validation needs to be on the group model instead of the user model, would this work? Ideally I'd like to update the associated groups without saving the record, do the validation, and THEN save the record.