在has_and_belongs_to_many中至少验证一个

时间:2021-03-18 11:08:22

I have a model with:

我有一个模型:

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...

但这似乎并没有给我想要的……

5 个解决方案

#1


32  

I would write custom validation:

我会写自定义验证:

validate :has_users?

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

That would do exactly that.

那样就能做到。

Note in rails 3+ you have to use:

注意,在rails 3+中,您必须使用:

  # rails 3+
  errors.add :base, "Model must have some users." if self.users.blank?

In rails 4+ there's a built-in shortcut, so you can simply do:

在rails 4+中有一个内置的快捷方式,所以你可以简单地做:

validates :users, presence: true

#2


28  

In rails 4 you can just do

在rails 4中,您可以这样做

validates :users, presence: true

#3


2  

In Rails 3.2.x:

在Rails 3.2.x:

validate :has_users?

def has_users?
  errors.add(:base, 'Error message') if self.users.blank?
end

#4


1  

Josh Susser wrote a plugin that adds a validates_existence_of method that does what you want. It ensures that a foreign key references a record that exists.

Josh Susser编写了一个插件,添加了一个validates_existence_of方法,它可以满足您的需要。它确保外键引用存在的记录。

#5


0  

Try:

试一试:

validates :users, :length => { :minimum => 1 }

#1


32  

I would write custom validation:

我会写自定义验证:

validate :has_users?

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

That would do exactly that.

那样就能做到。

Note in rails 3+ you have to use:

注意,在rails 3+中,您必须使用:

  # rails 3+
  errors.add :base, "Model must have some users." if self.users.blank?

In rails 4+ there's a built-in shortcut, so you can simply do:

在rails 4+中有一个内置的快捷方式,所以你可以简单地做:

validates :users, presence: true

#2


28  

In rails 4 you can just do

在rails 4中,您可以这样做

validates :users, presence: true

#3


2  

In Rails 3.2.x:

在Rails 3.2.x:

validate :has_users?

def has_users?
  errors.add(:base, 'Error message') if self.users.blank?
end

#4


1  

Josh Susser wrote a plugin that adds a validates_existence_of method that does what you want. It ensures that a foreign key references a record that exists.

Josh Susser编写了一个插件,添加了一个validates_existence_of方法,它可以满足您的需要。它确保外键引用存在的记录。

#5


0  

Try:

试一试:

validates :users, :length => { :minimum => 1 }