Categorization

Search bar was not working in the application. So I use the simple search method to implement search in the application. Instead of using any gem for the simple search functionality, I use the simple method to implement it.

Views

Lets take an example that we want to add the simple search in the category web page (category view). Add the simple search form in the app/views/category/index.html.erb or wherever you’d like to place the search form.

<%= form_tag(categories_path, :method => "get", id: "search-form") do %>
  <%= text_field_tag :search, params[:search], placeholder: "Search Categories" %>
  <%= submit_tag "Search" %>
<% end %>

Controllers

def index
  @categories = Category.all
  if params[:search]
   @categories = Category.search(params[:search]).order("created_at DESC")
  else
   @categories = Category.all.order('created_at DESC')
  end
end

Models

Add the query to search the field from the database. So add the query according to the requirements. Like I added the query on the name field of the category table.

def self.search(search)
  where("name LIKE ?", "%#{search}%") 
end

Advance Search using filterrific gem

I added the simple search in all the views execpt the article page because we add the advance search. But I faced some problems because we add the search on field of foriegn key that is we added the search on the category field in the article web page that fetch the value of the category from the category model. So here we need to add different logic to pass the query to the category table from the article controller. Here is the code that helps to add the search option in this situation.

We just add the logic in the controller of the article where it pass the query to the model to fetch the data. So need to write anything in the model. Search form is same as mentioned above.

# articles_controller.rb
def index
 if params[:search]
  @articles = Article
  .where(category_id: Category
  .where(name: params[:search]))
 else
  @articles = Article.all.order('created_at DESC')
 end
end

Here we check the category_id whose name matches the name of the searched category name.

filterrific gem

Filterrific gem makes it easy to filter, search, and sort your ActiveRecord lists. We just add the filtering using the dropdown but we can extend the functionality of the gem and add the sorting if required.

Step 1: Add the gem in your Gemfile.

 gem 'filterrific'

Step 2: Add the Filterrific ActionView API to display the list of matching records and the form to update filter settings.

Step 3: The Filterrific ActionController API initialize filter settings from params, persistence or defaults. Execute the ActiveRecord query to load the filtered records.

Step 4: Use the ActiveRecord model API to make your model filterrific and apply Filterrific to the model.

We can make the changes according to our requirements but we can use the above the links for the reference.

Thanks :).

Written on July 10, 2016