Validate has_many relationship with conditions ?

I need to validate that I have at least one relationship with a certain
condition. My code so far:

class User < ActiveRecord::Base
  belongs_to :user_type

class UserType < ActiveRecord::Base
  has_many :users
  has_many :admins, :source => :users, :conditions => "user_type_id = 1"

How do I validate that I have at least one admin when updating any user?

You can overwrite validate_on_update in your User model.

I'm not sure if this is exactly what you're looking to do, but it
might look something like:
def validate_on_update
    errors.add("User Type", "has no admins") if UserType.admins.count
== 0

*warning, not tested*

Thanks, I got pretty close with this suggestion..

turns out as I build this out more, i actually have users, groups, and
roles (on these groups), with role_types (1 is admin). in my roles
controller, I have actions which add/remove roles from a given group
(which correctly triggers my custom before_destroy method). However, I
can't seem to find how to display the errors from "before_destroy" upon
the redirect back to the group page. So far, I've been using
"error_messages_for :groups", similar to on my forms. I'm guessing
their is a problem displaying the errors generated by a "Role" in the
"Group" pages. suggestions?

class User < ActiveRecord::Base
  has_many :roles
  has_many :groups, :through => :roles

class Group < ActiveRecord::Base
  has_many :roles
  has_many :users, :through => :roles
  has_many :owners, :through => :roles, :source => :user, :conditions =>
"role_type_id = 1"

class RoleType < ActiveRecord::Base
  has_many :roles

class Role < ActiveRecord::Base
  belongs_to :user
  belongs_to :group
  belongs_to :role_type

  def before_destroy
    if (role_type_id.to_i == 1 && Group.find(group_id.to_i).owners.count
<= 1)
      errors.add(:group, "Groups require at least one owner")

class RolesController < ApplicationController
  def remove (group_id = params[:group_id], role_type_id =
params[:role_type_id], user_id =
    conditions = {:group_id => group_id, :role_type_id => role_type_id,
:user_id => user_id }
    redirect_to :controller => :groups, :action => "show", :id =>

gsterndale wrote: