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
end

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

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.

http://api.rubyonrails.org/classes/ActiveRecord/Validations.html#M001044

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
end

warning, not tested

On Aug 13, 5:45 pm, Mark S. [email protected]

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
end

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

class RoleType < ActiveRecord::Base
has_many :roles
end

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”)
false
end
end
end

class RolesController < ApplicationController
def remove (group_id = params[:group_id], role_type_id =
params[:role_type_id], user_id = @current_user.id)
conditions = {:group_id => group_id, :role_type_id => role_type_id,
:user_id => user_id }
Role.destroy_all(conditions)
redirect_to :controller => :groups, :action => “show”, :id =>
group_id
end
end

gsterndale wrote:

You can overwrite validate_on_update in your User model.

http://api.rubyonrails.org/classes/ActiveRecord/Validations.html#M001044

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
end

warning, not tested

On Aug 13, 5:45 pm, Mark S. [email protected]

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs