验证的至少一个在has_and_belongs_to_many [英] validate at least one in has_and_belongs_to_many

查看:157
本文介绍了验证的至少一个在has_and_belongs_to_many的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个模型:

has_and_belongs_to_many :users

我如何验证,该模型在模型中至少一个用户?我想:

How do I validate that the model has at least one user in the model? I tried:

validates_presence_of :users

但是,这似乎并没有给我什么,我想......

But that doesn't seem to give me what I want...

推荐答案

我会写自定义验证:

validate :has_users?

def has_users?
  errors.add_to_base "Model must have some users." if self.users.blank?
end

这将这样做。

That would do exactly that.

这篇关于验证的至少一个在has_and_belongs_to_many的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆