Rails检查开始时间和结束时间的多天范围

时间:2015-10-23 16:01:06

标签: sql ruby-on-rails activerecord

这是我的代码,用于检查用户是否与当前的工作申请有时间冲突。但是,在作业仅为1天之前,它们是多天,具有相同的开始时间和结束时间,以job.days表示。

    job = Job.find(params[:job_application][:job_id])
    id = job.id
    start_time = job.start_time
    end_time   = job.end_time
    overlaps   = @user.job_applications.joins(:job)
                   .where.not(job_id: id).where(approved: true, status: "SUCCESS")
                     .where("(jobs.start_time >= ? AND jobs.start_time <= ?) OR (jobs.end_time <= ? AND jobs.end_time >= ?)", start_time, end_time, end_time, start_time)
    unless overlaps.empty?
      render json: { error: "timeClash", status: 400}
    end

我正在尝试修改我的代码来执行此操作,但我似乎无法让它工作。我尝试了几种方法,但没有一种方法有效。如果不使用大量SQL,最简单的方法是什么?

1 个答案:

答案 0 :(得分:1)

我会使用验证来查看作业的时间段是否可用

class Job

  def validate(record)
    conflicting_jobs = Job.where("jobs.start_time < ? and jobs.end_time ? >", self.end_time, self.start_time).where(approved: true, status: 'SUCCESS')
    errors << conflicting_jobs.map {|j| "Job conflicts with #{j.name}"}
  end
end
相关问题