简体   繁体   English

Rails - 保存前的计数属性

[英]Rails - Count attribute before save

I have a class aluno that has :telephone attribute.我有一个具有 :telephone 属性的类 aluno。 I want to limit the same telephone number in 3 times.我想限制同一个电话号码 3 次。 It's just possible to have 3 telephone numbers in :telephone column.在 :telephone 列中只能有 3 个电话号码。

Before I create a new aluno, I would have to check if already have 3 alunos with the same telephone.在我创建一个新的aluno之前,我必须检查是否已经有3个aluno和同一个电话。

It would be like a "SELECT count(telephone) FROM alunos where telephone = '_FORM.telephone'它就像一个“SELECT count(telephone) FROM alunos where phone = '_FORM.telephone'

if count = 3 Message "Max 3 telephones already reached"如果计数 = 3 消息“已到达最多 3 个电话”

How would I do that?我该怎么做?

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

You can do something like this:你可以这样做:

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

I would use a custom method for this validation.我将使用自定义方法进行此验证。 Something like this should go into your Aluno model.像这样的东西应该进入你的 Aluno 模型。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM