Module: Heya::ActiveRecordRelationExtension

Defined in:
lib/heya/active_record_extension.rb

Constant Summary collapse

TABLE_REGEXP =
/heya_steps/

Instance Method Summary collapse

Instance Method Details

#build_arelObject

forward all params. Handles differences between 7.1 -> 7.2



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/heya/active_record_extension.rb', line 9

def build_arel(...) # forward all params. Handles differences between 7.1 -> 7.2
  arel = super(...)

  if table_name == "heya_campaign_memberships" && arel.to_sql =~ TABLE_REGEXP
    # https://www.postgresql.org/docs/9.4/queries-values.html
    values = Heya
      .campaigns.reduce([]) { |steps, campaign| steps | campaign.steps }
      .map { |step|
        ActiveRecord::Base.sanitize_sql_array(
          ["(?, ?)", step.gid, step.wait.to_i]
        )
      }

    if values.any?
      arel.with(
        Arel::Nodes::As.new(
          Arel::Table.new(:heya_steps),
          Arel::Nodes::SqlLiteral.new("(SELECT * FROM (VALUES #{values.join(", ")}) AS heya_steps (gid,wait))")
        )
      )
    end
  end

  arel
end