2016-05-02 203 views
-1

這是我的模型 -軌道4 - 自定義驗證錯誤

class Leave < ActiveRecord::Base 
belongs_to :staff 
validates :staff, :leave_type, :start_date, :end_date, :number_of_days, :approved_by, presence: true 
enum leave_type: {Medical: 0, Annual: 1, Urgent: 3, "Birth Leave": 4} 
validate :check_leave, :if => "self.number_of_days.present?" 




protected 

def check_leave 
    if self.leave_type = 0 
    if (self.number_of_days + LeaveAllocation.last.medical_leave_counter) > LeaveAllocation.last.medical_leave 
     self.errors.add(:number_of_days, "Days exceeded the limit") 
    end 
    end 
    if self.leave_type = 1 
    if (self.number_of_days + LeaveAllocation.last.annual_leave_counter) > LeaveAllocation.last.annual_leave 
     self.errors.add(:number_of_days, "Days exceeded the limit") 
    end 
    end 

end 

end 

當我嘗試運行驗證,它似乎只檢查第一個「0」,即使我將選擇更改爲「1」。任何幫助,將不勝感激!謝謝

+0

在創建和更新上,number_of_days是字段名稱(整數) –

+0

可以請您發佈完整的模型類嗎? @林林 –

+0

更新完整模型 –

回答

1

更改爲==在條件。

self.leave_type == 0 and 
self.leave_type == 1 
+0

在更改爲==後它不會生效。如果我使用=,它會驗證但只有第一個... –

+0

像這樣改變這條線'validate:check_leave,if: - > {self.number_of_days.present? }' –

+0

它仍然是一樣的。只驗證「0」的第一步, –