Method: Effective::DatatableColumnTool#size

Defined in:
app/models/effective/datatable_column_tool.rb

#size(collection) ⇒ Object

Not every ActiveRecord query will work when calling the simple .count Custom selects:

User.select(:email, :first_name).count will throw an error

Grouped Queries:

User.all.group(:email).count will return a Hash


91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
# File 'app/models/effective/datatable_column_tool.rb', line 91

def size(collection)
  count = (collection.size rescue nil)

  case count
  when Integer
    count
  when Hash
    count.size  # This represents the number of displayed datatable rows, not the sum all groups (which might be more)
  else
    if collection.klass.connection.respond_to?(:unprepared_statement)
      collection_sql = collection.klass.connection.unprepared_statement { collection.to_sql }
      (collection.klass.connection.exec_query("SELECT COUNT(*) FROM (#{collection_sql}) AS datatables_total_count").rows[0][0] rescue 1)
    else
      (collection.klass.connection.exec_query("SELECT COUNT(*) FROM (#{collection.to_sql}) AS datatables_total_count").rows[0][0] rescue 1)
    end.to_i
  end
end