Ruby on Rails - 使用“关联模型”属性验证属性

时间:2017-07-27 13:41:57

标签: ruby-on-rails

我有两种模式:

class ModelA < ApplicationRecord
  has_many: :model_b
end

class ModelB < ApplicationRecord
  belongs_to: :model_a
end

两个模型都有star_dateend_date,我想验证de ModelB日期是否在ModelA个日期之间。像这样:

class ModelB < ApplicationRecord
  belongs_to: :model_a
  validates :start_date, after_date: ModelA.start_date
end

我是Rails的新手,我不知道该怎么做。

谢谢!

2 个答案:

答案 0 :(得分:1)

您需要添加自定义验证

class ModelA < ActiveRecord::Base
  has_many: :model_b
end

class ModelB < ActiveRecord::Base
  belongs_to : model_a
  validates :is_between_parent_period

  private

  def is_between_parent_period
    unless start_date.between?(self.model_a.start_date, self.model_a.end_date) && end_date.between?(self.model_a.start_date, self.model_a.end_date)
      errors.add(:base, 'Must be between parent start date and end date')
    end
  end
end

答案 1 :(得分:0)

检查两个日期或时间范围A和B重叠是否需要涵盖很多情况:

A partially overlaps B
A surrounds B
B surrounds A
A occurs entirely after B
B occurs entirely after A

做简单检查重叠你可以在模型A中创建方法,然后将其他模型(模型b)作为参数传递

class ModelA < ActiveRecord::Base
  has_many: :model_b

  # Check if a given interval overlaps this interval    
  def overlaps?(other)
    (self.start_date - other.end_date) * (other.start_date - self.end_date) >= 0
  end
end