Reputation: 968
I try to create validation that checks times overlapping.
scope :overlapping_activity, ->(activity) { where("(start_on, end_on) OVERLAPS (?, ?)",
activity.start_on, activity.end_on }
validate :not_overlapping_activity
def not_overlapping_activity
if Activity.overlapping_activity(self).any?
errors.add(:base, "Zajęcie w tym okresie koliduje z innymi.")
end
end
Error:
ERROR: function pg_catalog.overlaps(time without time zone, time without time zone, unknown, unknown) is not unique
LINE 1: ...NT(*) FROM "activities" WHERE ((start_on, end_on) OVERLAPS (...
I found this topic: Rails 3.1: Querying Postgres for records within a time range, but I cannot use it in my solution. While I try add timestamps in scope, it shows another syntax errors. Could someone show me how to properly resolve my issue?
How I tried use timestamp:
scope :overlapping_activity, ->(activity) { where("(start_on::timestamp, end_on::timestamp) OVERLAPS (?, ?)",
timestamp activity.start_on, timestamp activity.end_on) }
Upvotes: 0
Views: 436
Reputation: 968
I achieved what I wanted by this method:
validate :not_overlapping_activity
def not_overlapping_activity
overlapping_activity = Activity.where(day_of_week: day_of_week)
.where(pool_zone: pool_zone)
overlapping_activity.each do |oa|
if (start_on...end_on).overlaps?(oa.start_on...oa.end_on)
errors.add(:base, 'In this period of time there is some activity.')
end
end
end
If someone has better solution please write. I want to be better and more clever :)
Upvotes: 1