Class: SnFilterable::Filterable::PolymorphicHelper

Inherits:
Object
  • Object
show all
Defined in:
lib/sn_filterable/filterable.rb

Overview

Helper class for handling polymorphic associations

Class Method Summary collapse

Class Method Details

.coalesce(models, column) ⇒ String

Coalesces the columns of a polymorphic association. Should be used in a relation that used the #joins helper.

Parameters:

  • models (Array<Class>)

    An array of the models that the polymorphic association applies to

  • column (String)

    The mutual column that exists in the models

Returns:

  • (String)

    the coalesce SQL function



275
276
277
278
279
280
281
282
283
284
285
286
# File 'lib/sn_filterable/filterable.rb', line 275

def self.coalesce(models, column)
  column = ActiveRecord::Base.connection.quote_column_name(column)

  sql_columns = []

  models.each do |model|
    associated_table = ActiveRecord::Base.connection.quote_table_name(model.table_name)
    sql_columns.push("#{associated_table}.#{column}")
  end

  "coalesce(#{sql_columns.join(', ')})"
end

.joins(relation, polymorphic_association, models) ⇒ ActiveRecord::Relation

Helper to join the polymorphic associated tables.

Parameters:

  • relation (ActiveRecord::Relation)

    The relation to apply the JOIN clause

  • polymorphic_association (Symbol, String)

    The name of the polymorphic association

  • models (Array<Class>)

    An array of the models that the polymorphic association applies to

Returns:

  • (ActiveRecord::Relation)


250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
# File 'lib/sn_filterable/filterable.rb', line 250

def self.joins(relation, polymorphic_association, models)
  table_name = ActiveRecord::Base.connection.quote_table_name(relation.table.name)
  polymorphic_association_id = ActiveRecord::Base.connection.quote_column_name("#{polymorphic_association}_id")
  polymorphic_association_type = ActiveRecord::Base.connection.quote_column_name("#{polymorphic_association}_type")

  models.each do |model|
    associated_table = ActiveRecord::Base.connection.quote_table_name(model.table_name)
    associated_type = model.name

    join_query = ActiveRecord::Base.sanitize_sql_array([
                                                        "LEFT OUTER JOIN #{associated_table} ON #{associated_table}.id = #{table_name}.#{polymorphic_association_id} AND #{table_name}.#{polymorphic_association_type} = ?",
                                                        associated_type
                                                      ])

    relation = relation.joins(join_query)
  end

  relation
end