Very Simple Search for Active Records

11 Jul

Okay, you might encounter a need to put very simple search for active record / model in your Rails app and here is it. Put this code in your active record model:

# A simple search method
def text
columns = [:name, :roll_no, :address, :city, :pin, :ph]
words = text.split(/\s+/)
query_array_2 = []
for word in words
query_array = []
for column in columns
query_array << "lower(#{column}) like '%#{word}%'"
query_array_2 << query_array.join(' or ')
query = query_array_2.collect{|e| "(#{e})"}.join(' and ')
self.where query

Leave a comment

Posted by on July 11, 2013 in Uncategorized


Tags: , , , ,

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: