Question

How do I do a (I think a custom) validation to determine that my model should have one of either of my STI models?

My models are like this:

class Account < ActiveRecord::Base
  has_many :users
  has_one :admin, class_name: Admin, dependent: :destroy
  has_many :members, class_name: Member, dependent: :destroy

  accepts_nested_attributes_for :admin, reject_if: proc { |attributes| attributes['name'].blank? }
  accepts_nested_attributes_for :members, reject_if: proc { |attributes| attributes['name'].blank? }

  # Validate should have one of either a member or a user
  # validates :users, ...
end

class User < ActiveRecord::Base
end

class Admin < User
end
class Member < User
end

I want to validate, when an account is created it should have one admin or at least one member.

I can provide more information if needed.

Thanks!

Was it helpful?

Solution

You might want to add an error if both of them are not present by using a custom validation.

class Account < ActiveRecord::Base
    validate :require_at_least_one_user

    def require_at_least_one_user
        errors.add(:user, "At least one user is required.") if self.admin.blank? && self.members.blank?
    end
end

OTHER TIPS

I would validate the presence of at least one user, regardless of its type.

Maybe this can help.

Good Luck.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top