module CQL::ActiveRecord::Relations::ManyToMany

Overview

Enhanced many-to-many association module with improved type safety, error handling, and performance optimizations.

Provides methods to define and manage many-to-many relationships through a join table with proper caching, lazy loading, and comprehensive error handling.

Included Modules

Defined in:

active_record/relations/many_to_many.cr

Macro Summary

Macros inherited from module CQL::ActiveRecord::Relations::BaseRelation

build_query(model_class) build_query, destroy_dependent(record, association) destroy_dependent, ensure_saved(record) ensure_saved, safe_db_operation(&block) safe_db_operation, safe_foreign_key(record, key, pk_type) safe_foreign_key, safe_id(record, pk_type) safe_id, underscore_name(class_name) underscore_name

Macro Detail

macro many_to_many(name, klass, join_through, foreign_key = nil, association_foreign_key = nil, dependent = :nullify, validate = true, autosave = false) #

Defines a many-to-many relationship between two models with enhanced features. This method will define a getter method that returns a ManyCollection. The collection can be used to add and remove records from the join table.

  • param : name (Symbol) - The name of the association
  • param : klass (Class) - The target model class
  • param : join_through (Symbol | Class) - The join table model or table name
  • param : foreign_key (Symbol) - Foreign key for this model in join table (optional)
  • param : association_foreign_key (Symbol) - Foreign key for target model in join table (optional)
  • param : dependent (Symbol) - What happens to the targets when the owner is deleted or the association cleared (:destroy, :delete_all, :nullify); the join rows are always removed
  • param : validate (Bool) - Whether to validate associated records
  • param : autosave (Bool) - Whether to automatically save associated records

Example

class Movie
  include CQL::ActiveRecord::Model(Int64)
  db_context AcmeDB, :movies

  property title : String = ""
  many_to_many :actors, Actor, join_through: MoviesActor,
    foreign_key: :movie_id, association_foreign_key: :actor_id,
    dependent: :destroy
end

class Actor
  include CQL::ActiveRecord::Model(Int64)
  db_context AcmeDB, :actors

  property name : String = ""
  many_to_many :movies, Movie, join_through: MoviesActor,
    foreign_key: :actor_id, association_foreign_key: :movie_id
end

class MoviesActor
  include CQL::ActiveRecord::Model(Int64)
  db_context AcmeDB, :movies_actors

  property movie_id : Int64?
  property actor_id : Int64?
end

[View source]