public
Created

Search Script

  • Download Gist
gistfile1.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
song.rb
def self.search(query)
if !query.to_s.strip.empty?
tokens = query.split.collect {|c| "%#{c.downcase}%"}
find_by_sql(["select s.* from songs s where #{ (["(lower(s.song_title) like ? or lower(s.song_lyrics) like ?)"] * tokens.size).join(" and ") } order by s.created_on desc", *(tokens * 2).sort])
else
[]
end
end
 
Once youve added the search method to your model, its even simpler to use.
 
search_controller.rb
def songs
@query = @params["query"]
@songs = Song.search(@query)
end

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.