Module: TimeRangeUniqueness::ModelAdditions
- Defined in:
- lib/time_range_uniqueness/model_additions.rb
Overview
The ‘ModelAdditions` module provides a custom validation for ensuring that time ranges in ActiveRecord models are unique across records, optionally scoped by other columns.
This module is intended to be included in ActiveRecord models and used to add validation methods to check for overlapping time ranges between records.
Example
class Event < ApplicationRecord
validates_time_range_uniqueness(
with: :event_time_range,
scope: :event_name,
message: 'cannot overlap with an existing event'
)
end
This example ensures that the ‘event_time_range` column in the `Event` model does not overlap with other records having the same `event_name`. If a new event’s time range overlaps, an error is added to the ‘event_time_range` field.
Options
-
:with
- The name of the time range column (required). -
:scope
- (Optional) An array of columns to scope the uniqueness check (e.g., event name). -
:message
- (Optional) A custom error message when validation fails. Defaults to ‘overlaps with an existing record’ if not provided.
Methods
-
validates_time_range_uniqueness
- Adds a validation for time range uniqueness. -
validate_records
- Internal method to perform the validation. -
time_range_column_overlapping?
- Internal method to check for overlapping time ranges.
When included in an ActiveRecord model, this module adds the ability to ensure that the specified time range does not overlap with other records’ time ranges, optionally scoped by additional fields.
Instance Method Summary collapse
-
#validates_time_range_uniqueness(options = {}) ⇒ Object
Adds a custom validation method to ensure that the specified time range column is unique across all records, optionally scoped by other columns.
Instance Method Details
#validates_time_range_uniqueness(options = {}) ⇒ Object
Adds a custom validation method to ensure that the specified time range column is unique across all records, optionally scoped by other columns.
Raises an ArgumentError if the :with
option is not specified.
50 51 52 53 54 55 56 57 |
# File 'lib/time_range_uniqueness/model_additions.rb', line 50 def validates_time_range_uniqueness( = {}) raise ArgumentError, 'You must specify the :with option with the time range column name' unless [:with] time_range_column = [:with] scope_columns = Array([:scope]) validate_records(time_range_column, scope_columns, ) end |