I have a bulk create form for academic years in my Rails application. I need to implement validations on this bulk form. The basic validations are working fine. I have a custom validation which does check the academic years do not overlap with each other.
For example, academic year 1 duration is sep 1 2022 - 31 aug 2023. So there cannot be another academic year within this or it cannot overlap during the academic year 1 duration.
class CustomValidator < ActiveModel::Validator
def validate(record)
return if overlapping_siblings(record).empty?
record.errors.add(options[:error_attribute], :overlapping_dates)
end
private
def overlapping_siblings(record)
scope = options[:scope] || -> { record.class.all }
scope
.call(record)
.where.not(id: record.id)
.where("? >= started_at AND ended_at >= ?", record.ended_at,
record.started_at)
end
end
This validator works fine for creating a single object. But for the bulk form, this does not work (which is expected). Because, if the bulk form tries to create 2 academic years with overlapping dates, as they are still not in the database, they are not validated against each other and hence the overlapping error is not caught.
What is the proper way to implement overlapping dates validation on bulk forms?