# Active record validations :: 如何验证 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 属性 : start_date,end_date,目的地
这是我的请假模型:
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 方法也检查 --> 居民是否已经有那个月的休假(存储在休假模型中)(月表示1 月、2 月等)然后它应该生成一个错误:
"You can't mark leave cause you have already marked leave for this month"
并且模型不应该存储那个假。
谢谢!
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?
您可以像这样添加另一种验证方法
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
我有两个模型...
models/Resident.rb : has_many: 叶
models/leave.rb: belongs_to: 居民
现在我想在模型属性创建之前验证离开模型属性..
leave.rb 属性 : start_date,end_date,目的地
这是我的请假模型:
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 方法也检查 --> 居民是否已经有那个月的休假(存储在休假模型中)(月表示1 月、2 月等)然后它应该生成一个错误:
"You can't mark leave cause you have already marked leave for this month" 并且模型不应该存储那个假。 谢谢!
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?
您可以像这样添加另一种验证方法
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