Class: Babik::QuerySet::SelectRelated

Inherits:
Object
  • Object
show all
Defined in:
lib/babik/queryset/components/select_related.rb

Overview

Delegate object that must deals with all the select_related particularities.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(model, selection_paths) ⇒ SelectRelated

Creates a new SelectRelated



14
15
16
17
18
19
20
21
# File 'lib/babik/queryset/components/select_related.rb', line 14

def initialize(model, selection_paths)
  @model = model
  @associations = []
  selection_paths = [selection_paths] if selection_paths.class != Array
  selection_paths.each do |selection_path|
    @associations << Babik::Selection::SelectRelatedSelection.new(@model, selection_path)
  end
end

Instance Attribute Details

#associationsObject (readonly)

Returns the value of attribute associations.



11
12
13
# File 'lib/babik/queryset/components/select_related.rb', line 11

def associations
  @associations
end

#modelObject (readonly)

Returns the value of attribute model.



11
12
13
# File 'lib/babik/queryset/components/select_related.rb', line 11

def model
  @model
end

Instance Method Details

Return the next object and its related objects Requires a result set of the query that selects all object attributes and the rest of attributes of the associated objects.

Parameters:

  • result_set (ResultSet)

    Result with the query that loads all the required objects (main and related ones).

Returns:

  • (ActiveRecord::Base, Hash{selection_path: ActiveRecord::Base})

    Return and object with its associated objects.



40
41
42
43
44
45
46
47
48
# File 'lib/babik/queryset/components/select_related.rb', line 40

def all_with_related(result_set)
  result_set.map do |record|
    object = instantiate_model_object(record)
    associated_objects = @associations.map do |association|
      [association.selection_path, instantiate_associated_object(record, association)]
    end
    [object, associated_objects.to_h.symbolize_keys]
  end
end

#left_joins_by_aliasHash{table_alias: String}

Return the joins that are needed according to the associated path

Returns:

  • (Hash{table_alias: String})

    Left joins by table alias.



25
26
27
28
29
30
31
# File 'lib/babik/queryset/components/select_related.rb', line 25

def left_joins_by_alias
  left_joins_by_alias = {}
  @associations.each do |association|
    left_joins_by_alias.merge!(association.left_joins_by_alias)
  end
  left_joins_by_alias
end