1

我有以下的用户模型一个Rails应用程序:Rails的自定义验证在多个属性

卡车 用户

的卡车属于具有下列关联用户:

class Unit < ActiveRecord::Base 
    belongs_to :primary_crew_member, :foreign_key => :primary_crew_member_id, :class_name => 'User' 
    belongs_to :secondary_crew_member, :foreign_key => :secondary_crew_member_id, :class_name => 'User' 
end 

Truck模型我有验证,以确保primary_crew_member_idsecondary_crew_member_id始终存在,因为Truck不能有用户/机组人员。

我希望能够做的是以下几点:

  • 验证主要或次要机组成员(用户)没有分配到任何其他卡车
  • 拓展上验证我需要确定卡车A上的John Doe是否是主要船员,他不能被分配到任何其他卡车上的主要或次要位置。
  • 进一步扩大李四不应该能够采取两种中小学插槽在给定的卡车(双排班)

我一派,并想出了一个验证像主插槽验证所以:

验证:primary_multiple_assignment

def primary_multiple_assignment 
     if Truck.has_primary(primary_crew_member_id) 
     errors.add(:base, "User has already been assigned to another truck.") 
     end 
    end 

    def self.has_primary(primary_crew_member_id) 
     primary = Truck.where(primary_crew_member_id: primary_crew_member_id).first 
     !primary.nil? 
    end 

这似乎是工作,我可以确保没有用户被分配到一个主卡槽任何卡车除了单一的一个。但是,我需要能够满足我的验证要求,如上所述。所以基本上我试图验证多个列在一个单一的方法,但我不知道如何工作。

我已经阅读了Rails自定义验证指南,我几乎卡住了。任何您可能需要帮助的信息将不胜感激。与此同时,我会继续修补和搜索以找到解决方案。

回答

0

您可以采用两种验证的做到这一点:

# validate that the primary or secondary crew member (user) is not assigned to 
# any other truck 
validates :primary_crew_member, uniqueness: true 
validates :secondary_crew_member, uniqueness: true 

# validate that the primary crew member can't be secondary crew member on any 
# truck (including current one) 
validate :primary_not_to_be_secondary 

# validate that the secondary crew member can't be primary crew member on any  
# truck (including current one) 
validate :secondary_not_to_be_primary 

def primary_not_to_be_secondary 
    if Truck.where(secondary_crew_member_id: primary_crew_member_id).present? 
     errors.add(:base, "Primary crew member already assigned as secondary crew member.") 
    end 
end 

def secondary_not_to_be_primary 
    if Truck.where(primary_crew_member_id: secondary_crew_member_id).present? 
     errors.add(:base, "Secondary crew member already assigned as primary crew member.") 
    end 
end 
+0

谢谢您的回答,我从那以后它可以处理一些不同的边缘情况下,我也没多想拿出自己的解决方案。很快会发布我的答案。 – nulltek