Skip to content

Instantly share code, notes, and snippets.

@radar
Created November 5, 2010 06:51
Show Gist options
  • Save radar/663752 to your computer and use it in GitHub Desktop.
Save radar/663752 to your computer and use it in GitHub Desktop.

WildcardSearch is a module from Ennova's Envision application used with permission. The purpose of this module is to allow users to search fields of all records of a model for certain keywords.

The usage example is in usage.rb for this gist and the code uses ARel extensively.

The includes method is from ARel and does a LEFT OUTER JOIN on the association specified's table, providing we fetch fields from that table in the where. For more information see this post: http://ruby.ryanbigg.com/post/1468788928/left-outer-join-with-arel

class Event < ActiveRecord::Base
include WildcardSearch
belongs_to :originator, :class_name => "User"
end
Event.includes(:originator).wildcard_search(:name, :description, :originator => [:username], text)
module WildcardSearch
def wildcard_search(*fields)
# Get what we're looking for
text_parts = fields.pop.split(/\s/).map { |part| "%#{part}%" }
cnds = nil
fields.each do |field|
field = { self.table_name => [field] } if field.is_a? Symbol
field.each do |table, columns|
assoc = reflect_on_association table
table = if assoc && assoc.macro == :belongs_to
Table assoc.table_name, :as => "#{assoc.name.to_s.tableize}_#{assoc.table_name}"
else
Table table
end
columns.each do |column|
text_parts.each do |part|
cnd = table[column].matches(part)
cnds = cnds ? cnds.or(cnd) : cnd
end
end
end
end
where(cnds)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment