我如何进行(我认为是自定义)验证以确定我的模型应该具有我的任何一种STI模型?
我的模特是这样的:
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
我想验证,创建帐户时,应该有一个管理员或至少一个成员。
如果需要,我可以提供更多信息。
谢谢!
答案 0 :(得分:1)
如果使用自定义验证不存在错误,则可能需要添加错误。
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
答案 1 :(得分:0)