Module: TimeRangeUniqueness::MigrationAdditions
- Defined in:
- lib/time_range_uniqueness/migration_additions.rb
Overview
This module provides methods for adding and managing time range uniqueness constraints in ActiveRecord migrations.
It allows you to add an exclusion constraint to ensure that time ranges do not overlap within a table.
Example
class AddEventTimeRangeUniqueness < ActiveRecord::Migration[6.1]
def change
add_time_range_uniqueness :events,
with: :event_time_range,
scope: :event_name,
column_type: :tstzrange,
name: 'unique_event_time_ranges'
end
end
Options
-
:with
- The name of the column that stores the time range (required). -
:scope
- (Optional) An array of columns to scope the uniqueness check. -
:column_type
- (Optional) The type of the time range column (default: :tstzrange). -
:name
- (Optional) The name of the constraint.
Methods
-
add_time_range_uniqueness(table, options = {}) - Adds the time range column and the exclusion constraint.
-
CommandRecorder
- Records the ‘add_time_range_uniqueness` command so it can be replayed during rollback.
Defined Under Namespace
Modules: CommandRecorder
Instance Method Summary collapse
-
#add_time_range_uniqueness(table, options = {}) ⇒ Object
Adds a time range column and an exclusion constraint to the specified table.
Instance Method Details
#add_time_range_uniqueness(table, options = {}) ⇒ Object
Adds a time range column and an exclusion constraint to the specified table.
This method creates or modifies a column to store time ranges and ensures that no two time ranges overlap for records with the same scoped columns.
45 46 47 48 49 50 51 52 53 54 55 |
# File 'lib/time_range_uniqueness/migration_additions.rb', line 45 def add_time_range_uniqueness(table, = {}) time_range_column = [:with] || :time_range scope_columns = Array([:scope]) column_type = :tstzrange constraint_name = [:name] || generate_constraint_name(table, scope_columns, time_range_column) reversible do |dir| dir.up { apply_up_migration(table, time_range_column, column_type, , constraint_name, scope_columns) } dir.down { apply_down_migration(table, time_range_column, constraint_name) } end end |