Class: RESTFramework::ModelSearchFilter

Inherits:
BaseFilter
  • Object
show all
Defined in:
lib/rest_framework/filters.rb

Overview

Multi-field text searching on models.

Constant Summary collapse

DEFAULT_SEARCH_COLUMNS =
%w[name email title description note]

Instance Method Summary collapse

Methods inherited from BaseFilter

#initialize

Constructor Details

This class inherits a constructor from RESTFramework::BaseFilter

Instance Method Details

#_get_fieldsObject

Get a list of search fields for the current action. Fallback to columns but only grab a few common string-like columns by default.



122
123
124
125
126
127
128
129
130
131
# File 'lib/rest_framework/filters.rb', line 122

def _get_fields
  if search_fields = @controller.class.search_fields
    return search_fields
  end

  columns = @controller.class.get_model.columns_hash.keys
  return @controller.get_fields(fallback: true).select { |f|
    f.in?(DEFAULT_SEARCH_COLUMNS) && f.in?(columns)
  }
end

#get_filtered_data(data) ⇒ Object

Filter data according to the request query parameters.



134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
# File 'lib/rest_framework/filters.rb', line 134

def get_filtered_data(data)
  search = @controller.request.query_parameters[@controller.class.search_query_param]

  if search.present?
    if fields = self._get_fields.presence
      # MySQL doesn't support casting to VARCHAR, so we need to use CHAR instead.
      data_type = if data.connection.adapter_name =~ /mysql/i
        "CHAR"
      else
        # Sufficient for both PostgreSQL and SQLite.
        "VARCHAR"
      end

      # Ensure we pass user input as arguments to prevent SQL injection.
      return data.where(
        fields.map { |f|
          "CAST(#{f} AS #{data_type}) #{@controller.class.search_ilike ? "ILIKE" : "LIKE"} ?"
        }.join(" OR "),
        *(["%#{search}%"] * fields.length),
      )
    end
  end

  return data
end