#Active record验证::如何在Rails(custom_validations)中验证日期属性?

时间:2016-04-06 14:24:16

标签: ruby-on-rails ruby ruby-on-rails-3 activerecord activemodel

我有两个型号......

models / Resident.rb :has_many:leaves

models / leave.rb :belongs_to:resident

现在我要验证的是在模型属性创建之前离开它们。

leave.rb 属性 start_date,end_date,destination

这是我的休假模式

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 方法来检查 - &gt;如果居民已经休假(存储在假期模型中),那个月(月份就是jan,feb等)那么它应该产生一个错误:

“你不能标记请假,因为你已经在本月标记了假期” 和模型不应该存储该离开。 谢谢!

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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?