Module: Klastera::Concerns::Clusterizable::ClassMethods
- Defined in:
- app/models/klastera/concerns/clusterizable.rb
Instance Method Summary collapse
-
#batch_assign_clusters(entity_ids, cluster_ids) ⇒ Object
Batch update cluster assignments for multiple entities More efficient than individual updates.
- #cluster_entity_params ⇒ Object
-
#preload_clusters(collection) ⇒ Object
Efficiently preload clusters for a collection of entities This prevents N+1 queries when calling clusters_string_separated_by on multiple entities.
Instance Method Details
#batch_assign_clusters(entity_ids, cluster_ids) ⇒ Object
Batch update cluster assignments for multiple entities More efficient than individual updates
89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 |
# File 'app/models/klastera/concerns/clusterizable.rb', line 89 def batch_assign_clusters(entity_ids, cluster_ids) return if entity_ids.empty? || cluster_ids.empty? # Clear existing assignments Klastera::ClusterEntity.where( entity_type: self.name, entity_id: entity_ids ).destroy_all # Create new assignments cluster_assignments = [] entity_ids.each do |entity_id| cluster_ids.each do |cluster_id| cluster_assignments << { entity_type: self.name, entity_id: entity_id, cluster_id: cluster_id, created_at: Time.current, updated_at: Time.current } end end Klastera::ClusterEntity.insert_all(cluster_assignments) if cluster_assignments.any? end |
#cluster_entity_params ⇒ Object
67 68 69 |
# File 'app/models/klastera/concerns/clusterizable.rb', line 67 def cluster_entity_params [ :cluster_id, { cluster_entities_attributes: [:id, :cluster_id, :_destroy] } ] end |
#preload_clusters(collection) ⇒ Object
Efficiently preload clusters for a collection of entities This prevents N+1 queries when calling clusters_string_separated_by on multiple entities
75 76 77 78 79 80 81 82 83 |
# File 'app/models/klastera/concerns/clusterizable.rb', line 75 def preload_clusters(collection) return collection if collection.empty? ActiveRecord::Associations::Preloader.new.preload( collection, cluster_entities: :cluster ) collection end |