Ruby on rails RubyonRails-验证属性和关联的模型属性

Ruby on rails RubyonRails-验证属性和关联的模型属性,ruby-on-rails,Ruby On Rails,我有两种型号: class ModelA < ApplicationRecord has_many: :model_b end class ModelB < ApplicationRecord belongs_to: :model_a end 我是Rails新手,不知道该怎么做 谢谢 您需要添加自定义验证 class ModelA < ActiveRecord::Base has_many: :model_b end class ModelB < Act

我有两种型号:

class ModelA < ApplicationRecord
  has_many: :model_b
end

class ModelB < ApplicationRecord
  belongs_to: :model_a
end
我是Rails新手,不知道该怎么做


谢谢

您需要添加自定义验证

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
classmodela
检查两个日期或时间范围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
classmodela=0
结束
结束

您的答案很有用,我将使用此代码进行验证。谢谢
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