MMeirelles
MMeirelles

Reputation: 83

Rails - Count attribute before save

I have a class aluno that has :telephone attribute. I want to limit the same telephone number in 3 times. It's just possible to have 3 telephone numbers in :telephone column.

Before I create a new aluno, I would have to check if already have 3 alunos with the same telephone.

It would be like a "SELECT count(telephone) FROM alunos where telephone = '_FORM.telephone'

if count = 3 Message "Max 3 telephones already reached"

How would I do that?

Upvotes: 2

Views: 274

Answers (3)

Mika
Mika

Reputation: 1479

I would use a custom method for this validation. Something like this should go into your Aluno model.

validate :telefone_count

def telefone_count
  tele_count = Aluno.where(telefone: telefone).count
  if tele_count >= 3
    errors.add(:telefone, "Already 3 or more with the same telefone.")
  end
end

Upvotes: 0

redDragonzz
redDragonzz

Reputation: 1571

You can do something like this:

a = alunos.find_all_by_telefone(params[:telefone])
if a.count >= 3:
   message = "Max reached"
else:
   entity.save

Upvotes: 0

Jason Kim
Jason Kim

Reputation: 19031

Yes, you need to create a custom validator in your model. It would look something like below.

class Aluno < ActiveRecord::Base
  ...

  validate :there_are_three_max_telefone

  def there_are_three_max_telefone
    alunos = Aluno.find_all_by_telefone(telefone)
    if alunos.count >= 3
      errors[:base] << "Max 3 telefones already reached"
    end
  end
end

Upvotes: 2

Related Questions