0

我有兩個型號...#活動記錄驗證::如何驗證Rails(custom_validations)中的日期屬性?

型號/ Resident.rb:的has_many:葉

型號/ leave.rb:belongs_to的:居民現在

我想要在創建模型屬性之前驗證它們。

leave.rb屬性日期,結束日期,目的地

這裏是我的休假模式

class Leave < ActiveRecord::Base 
    belongs_to :resident 
    validates :destination,presence:true 
    validates :end_date,presence: true 
    validates :start_date,presence: true 
    before_create :check_correct_leave 

    private 

    def check_correct_leave 

    if resident.hostel.hostel=='J' 
    (self.end_date - self.start_date).to_i == 4 || (self.end_date - self.start_date).to_i == 5 

    else 
    errors.add(:start_date, "Leave are granted only 4 or 5 days") 
    end 

    end 

end 

我想check_correct_leave方法也籤 - >如果居民已經有一個月的假期(存儲在假期模型中)(月意味着jan,feb等),那麼它應該產生一個錯誤:

「你不能因爲你本月已經打上假期而留下假期」 和模型不應該存放那個假期。 謝謝!

回答

1

您可以添加這樣

validate :check_leaves_in_same_month 


def check_leaves_in_same_month 
    if self.resident.leaves.where('start_date > ?', self.start_date.beginning_of_month).any? 
     errors.add("You can't mark leave cause you have already marked leave for this month") 
    end 
end 
+0

它正在工作,但林從我的控制器閃存錯誤: 'def創建 @ leave = current_user.resident.leaves.create(leave_params) if @ leave.save flash [:info] =「離開成功標記」 redirect_to leaves_path else flash [:danger] =「標記你的再次離開(不是離開)!」 redirect_to的new_leave_path 結束 end' **閃光燈[:危險=「!標記你的離開再次(不是vaild離開)」 **這一個錯誤.. –

+0

如果你想顯示錯誤消息補充說,你可以更改閃光燈[:危險]爲'閃光[:危險] = @ leave.errors.full_messages.first' –

+0

是的,這是工作,但當我創建一個假期它顯示我錯誤 - > **你可以' t標誌離開因爲你本月已經有明顯的假期** 但是假期正在被儲存在數據庫中!如何解決它? –

0
def has_leave_for_the_same_month? 
    resident.leaves.any? do |other_leave| 
    other_leave.start_date.month == leave.start_date.month 
    end 
end 

errors.add(...) if has_leave_for_the_same_month? 
+0

另一種驗證方法不工作... –

+0

http://apidock.com/ruby/Enumerable/any%3F –

+0

您應該使用任何?塊 –