【问题标题】:Rails Custom Validation for Associated Model关联模型的 Rails 自定义验证
【发布时间】:2018-10-02 21:26:20
【问题描述】:

我有两个模型,分别称为 Task 和 Employee,它们具有多对多关系。

class Task < ApplicationRecord
  has_and_belongs_to_many :employees
end

...

class Employee < ApplicationRecord
  has_and_belongs_to_many :tasks
end

我想要这样的功能。员工不能在同一时间段内执行多项任务。任务模型具有 start_date 和 duration 字段,因此我需要字段来进行此验证。

@task = Task.create(start_date:Time.zone.now, duration:2)
@employee.tasks << @task

当我将新任务推送到员工的任务时,我想验证该员工是否已经与新任务发生冲突。我怎样才能做到这一点?

谢谢。

【问题讨论】:

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


    【解决方案1】:

    这是一种方法,不是最好的,但应该可以。在 Task 模型中,添加自定义验证以检查定义期间是否存在同一 User 的其他任务。

    class Task
    
    validate :check_overlapping_tasks
    
    
    def check_overlapping_tasks
      end_date = start_date + duration
            Task.where(user_id: user_id)
                .where.not(id: id)
                .where("(start_date BETWEEN ? AND ? ) OR  (DATE_ADD(created_at, INTERVAL ? MINUTE)  BETWEEN ? AND ?)", start_date, end_date, duration, start_date, end_date)
       if overlapped_tasks.count > 0 
         errors.add(:base, 'User X has tasks in this period')
       end
     end
    
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多