Skip to content

Instantly share code, notes, and snippets.

@dodops
Last active August 29, 2015 14:15
Show Gist options
  • Save dodops/ad658da87a17bb1d5a04 to your computer and use it in GitHub Desktop.
Save dodops/ad658da87a17bb1d5a04 to your computer and use it in GitHub Desktop.
#Credits to Carlos Souza
#I've made some changes for search works in strings with special caracters like accents.
#In the model
scope :search, ->(keyword) { where('keywords LIKE ?', "%#{I18n.transliterate(keyword.downcase)}%") if keyword.present? }
before_save :set_keywords
validates :title, :author, :description, presence: true
protected
def set_keywords
keywords = [title, author, description].map(&:downcase).join(' ')
self.keywords = I18n.transliterate(keywords)
end
# In controller you will do something like this
def index
@resources = Resorce.search(params[:keyword])
end
@dodops
Copy link
Author

dodops commented Feb 15, 2015

Before all that, I created a migration that add a text field named "keywords" to the table I'm going to perform the search.

title, author and description are examples of fields that I have in the model and the search will perform in those fields. Replace it with any field that you want the search to be performed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment