繁体   English   中英

#活动记录验证::如何在Rails(custom_validations)中验证日期属性?

[英]# Active record validations : : How to validate date attributes in Rails(custom_validations)?

我有两个模特...

models / Resident.rb :has_many:叶子

models / 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等),那么它应该生成以下错误:

“您不能标记休假,因为您已经标记了本月休假”,并且模型不应存储该休假。 谢谢 !

您可以添加其他类似的验证方法

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
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?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM