Last active
August 29, 2015 14:15
-
-
Save dodops/ad658da87a17bb1d5a04 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.