Egon Braun
Egon Braun

Reputation: 190

Rails 4 - Custom validation method not being called

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?

Upvotes: 0

Views: 1972

Answers (2)

K M Rakibul Islam
K M Rakibul Islam

Reputation: 34338

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.

Upvotes: 3

x6iae
x6iae

Reputation: 4164

You are adding two errors in one validation. maybe you can split this into separate validations for easy debugging:

validates :team_id, presence: :true
validate :belong_to_team, :assignee_part_of_team

private
def belong_to_team
  errors[:team] << 'Equipe não existe' unless self.team
end

def assignee_part_of_team
  errors[:assignee] << 'Responsável não faz parte da equipe' unless self.team and self.team.users.include?(self.assignee)
end

Then you can know which is causing the fault here.

Upvotes: 0

Related Questions