Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

validate at least one in has_and_belongs_to_many

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

like image 786
cmaughan Avatar asked Jun 04 '09 11:06

cmaughan


4 Answers

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+
  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:

validates :users, presence: true
like image 178
Jakub Troszok Avatar answered Nov 09 '22 23:11

Jakub Troszok


In rails 4 you can just do

validates :users, presence: true
like image 33
Jaco Pretorius Avatar answered Nov 10 '22 01:11

Jaco Pretorius


In Rails 3.2.x:

validate :has_users?

def has_users?
  errors.add(:base, 'Error message') if self.users.blank?
end
like image 44
Wojtek B. Avatar answered Nov 10 '22 00:11

Wojtek B.


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.

like image 35
John Topley Avatar answered Nov 09 '22 23:11

John Topley