I am trying to implement a check to see if two opening_hours are overlapping with each other upon create. When you create a store, you can add only one opening_hour for Monday like 10:00 until 20:00, or two like Monday 10:00 - 13:00 and Monday 14:00-20:00. In the last case, it creates two entries with the same day, which is fine but I need to check if the opening_hours are overlapping.
I have a Store and OpeningHour model :
class Store < ApplicationRecord
has_many :opening_hours, dependent: :destroy
validates :name, presence: true
accepts_nested_attributes_for :opening_hours, reject_if: ->(opening_hours) { opening_hours[:day].blank? && opening_hours[:open].blank? },
allow_destroy: true
end
class OpeningHour < ApplicationRecord
belongs_to :store
validates :day, acceptance: { accept: Date::DAYNAMES }, allow_blank: true
end
And here is the schema:
create_table "opening_hours", force: :cascade do |t|
t.bigint "store_id", null: false
t.string "day"
t.time "open"
t.time "close"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["store_id"], name: "index_opening_hours_on_store_id"
end
create_table "stores", force: :cascade do |t|
t.string "name"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
I tried to use the validate overlap gem, but it was not working like I wanted :
validates :open, :close, overlap: { exclude_edges: %w[open close], scope: :store_id }
The problem with the gem is that I need to scope with the store_id I am currently creating, and also to check if there are two opening_hours created for Monday for example, so I need to scope with the day. However when I scope with the store_id nothing is happening, but when I scope with the day, I cannot create anything.
I tried to create a custom scope to add in query_options, but it didn't work either... And all the solution I checked, I cannot make them work. Do I need to scope something else? Or to not use the gem at all? Thanks for the help!