I have a validation method that should validate whether an user is part of a team. If it is not part of the team it should add an error and thus failing to save the record.
This is the current method that is inside the model:
def assignee_must_be_part_of_team
unless assignee_id.blank?
team = Team.find(self.team_id)
errors.add(:team, 'Equipe não existe') unless team
user = team.users.find(self.assignee_id)
errors.add(:assignee_id, 'Responsável não faz parte da equipe') unless user
end
end
And I am registering it in my model with this:
validate :assignee_must_be_part_of_team, on: :save
However, this method is not being even called when I save a new record! I even tried to add some logs to it but nothing happens and the record is being saved anyway.
Am I missing anything here?
Use create
or update
as the value of :on
option.
Change this:
validate :assignee_must_be_part_of_team, on: :save
To:
validate :assignee_must_be_part_of_team, on: :create
or:
validate :assignee_must_be_part_of_team, on: :update
If you want your validation to run for both create
and update
actions, then you don't even need to specify the :on
option at all, because that's the default behaviour. So, just this should work:
validate :assignee_must_be_part_of_team
See the documentation here for more information.