【问题标题】:# Active record validations : : How to validate date attributes in Rails(custom_validations)?# 活动记录验证: : 如何在 Rails(custom_validations) 中验证日期属性?
【发布时间】:2016-04-06 14:24:15
【问题描述】:

我有两个模型...

models/Resident.rb:has_many:叶子

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 方法也检查 --> 如果居民已经有一个月的休假(存储在休假模型中)(月份表示 1 月、2 月等),那么它应该产生一个错误:

“您无法标记请假,因为您已经标记了本月的请假” 并且模型不应该存储该离开。 谢谢!

【问题讨论】:

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


    【解决方案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
    

    【讨论】:

    • 它正在工作,但我的控制器收到 flash 错误:def create @leave=current_user.resident.leaves.create(leave_params) if @leave.save flash[:info] = "Leave successfully marked" redirect_to leaves_path else flash[:danger] = "Mark Your Leave Again (Not a vaild Leave) !" redirect_to new_leave_path end end flash[:danger] = "Mark Your Leave Again (Not a vaild Leave)!" 这个一个错误..
    • 如果要显示添加的错误信息,可以将flash[:danger]改为flash[:danger]= @leave.errors.full_messages.first
    • 是的,这是有效的,但是当我创建休假时,它显示错误 --> 您无法标记休假,因为您已经标记了本月的休假,但是离开正在存储在数据库中!如何解决?
    • 啊好的,你需要把current_user.resident.leaves.create(leave_params)改成current_user.resident.leaves.new(leave_params),因为创建的假期已经是同月的start_date,所以不能保存两次
    • 但是 before_create 不行吗?如果我将其更改为 validates 那么它将保存任何日期差异的叶子,而不是由我制作的函数:check_correct_leave
    【解决方案2】:
    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?
    

    【讨论】:

    • 你应该使用任何?阻止
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-10
    • 2010-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多