我有一个模型(ProjectedSquad)属于另一个具有许多不同外键的模型(SoldierBio)。我想验证某些字段是否具有仅在行中出现一次的uid值,而其他字段不需要具有唯一值。
是否有高效或Rails方式来运行这些复杂的验证?
截至目前,自定义验证包含嵌套的每个块,并检查每个字段是否包含其他字段中包含的值。它很慢而且很乱,但确实有效。还有更好的方法吗?
这两个对象之间的关系虽然很奇怪,但必须以这种方式构建(ProjectedSquad属于SoldierBio,如lt,lt2,col,gen等......)。
class ProjectedSquad < ActiveRecord::Base
belongs_to :soldier_bio, foreign_key: :lt_uid
belongs_to :soldier_bio, foreign_key: :lt2_uid
belongs_to :soldier_bio, foreign_key: :col_uid
belongs_to :soldier_bio, foreign_key: :maj_uid
belongs_to :soldier_bio, foreign_key: :gen_uid
belongs_to :soldier_bio, foreign_key: :pfc_uid
belongs_to :soldier_bio, foreign_key: :cpl_uid
belongs_to :soldier_bio, foreign_key: :medic_uid
belongs_to :soldier_bio, foreign_key: :radio_uid
belongs_to :soldier_bio, foreign_key: :tech_uid
belongs_to :soldier_bio, foreign_key: :sonar_uid
RANKS = [:lt_uid, :lt2_uid, :col_uid, :maj_uid, :gen_uid, :pfc_uid, :cpl_uid]
SPECIALS = [:radio_uid, :tech_uid, :sonar_uid, :medic_uid]
validate :unique_rank
validate :multiple_specials
validate :multiple_specials_is_officer
private
def unique_rank
## can only have one rank
# RANKS.each do |rank_uid|
# if array of rank uid values includes self.rank
# self.errors.add(rank_uid, "can't have multiple ranks")
# end
end
def specials
## can have same uid value both for a rank and a special
## cannot have same uid in multiple specials
end
def multiple_specials_is_officer
## same uid for 2 specials
## uid cannot appear in pfc_uid or cpl_uid, but can in one other rank field
end
end