views:

187

answers:

2

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

A: 

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.

John Topley
That looked promising, but it didn't work:"Cannot validate existence of :users because it is not a belongs_to association." Looks like it's only for belongs_to...
cmaughan
That's correct. What's on the other end of your association?
John Topley
+2  A: 

I would write custom validation:

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.

j t