Module: Angsa::Searching

Included in:
Base
Defined in:
lib/angsa/searching.rb

Instance Method Summary collapse

Instance Method Details

#apply_search(records, params) ⇒ Object



3
4
5
6
7
8
9
10
11
12
13
# File 'lib/angsa/searching.rb', line 3

def apply_search(records, params)
  return records unless params[:search]

  conditions, values, associations = build_search_conditions_values_and_associations(columns, records, params)
  
  associations.each do |association|
    records = records.joins(association.to_sym)
  end
  
  records.where(conditions.join(' OR '), values)
end

#build_search_conditions_values_and_associations(columns, records, params) ⇒ Object



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/angsa/searching.rb', line 15

def build_search_conditions_values_and_associations(columns, records, params)
  conditions = []
  values = {}
  associations = []

  columns.each do |column|
    next unless column[:searchable]  # Skip columns that aren't searchable

    source_parts = column[:source].split('.')
    if source_parts.size == 1
      # This is an attribute of the Course model
      if column[:type] == :string
        conditions << "LOWER(#{records.all.table_name}.#{source_parts.first}) LIKE :search"
      end
    else
      # This is an attribute of an associated model
      association, attribute = source_parts
      if column[:type] == :string
        conditions << "LOWER(#{association.pluralize}.#{attribute}) LIKE :search"
        associations << association
      end
    end
  end

  values[:search] = "%#{params[:search].downcase}%"
  
  return conditions, values, associations.uniq
end