How to implement filtering for my Rails app

Hi, I’m working on a Rails app, PosPlus (https://github.com/acandael/posplus-rails)

It’s an app for a university research group. The app has a cms functionality (under the admin folders).

For administering the publications, I want to enable filtered search with a select box. So that administrators can select a category in the select box so that the controller filters the publications and sends only the publications of selected category to the index view.

Anyone know some good reference code for implementing this filtered search?

thanks for your help,

Anthony

ok, made some progress here, this is what I did:

I created a form for filtering:

<%= form_tag admin_publications_path, method: "get" do %>
  <%= select "publication", "category", options_for_select(options_for_categories, selected: params[:publication][:category]), {prompt: 'Select Category'} %>
  <%= submit_tag "Filter", name: nil %>
<% end %>

In my PublicationsController I check if filter params came with the request:

def index
  if params[:publication]
    @publications = Publication.filter(params[:publication][:category])
  else
    @publications = Publication.all
  end 
end

if filter requests are available, I call the Class method ‘filter’

class Publication < ActiveRecord::Base
...

  def self.filter(filter)
    if filter
      where(category_id: filter)
    end
  end
...
end

In the Class method filter, I load all publications that have a category_id equal to the one that was passed in with the filter params.

This works, but there is still a problem with my Filter form. Right now, if you do a filtered search, there now way to get all publications shown again, so in my Filter selected box I should need a ‘All’ option that brings back all publications.

Does anyone know how I can add this “All” option to my select box?

thanks for your help,

Anthony

just improved my filter form

I now filters on a onchange event:

  <%= form_tag admin_publications_path, method: "get", id: "filter", class: "filter" do %>
    <%= label_tag "Category" %>
    <%= select "publication", "category", options_for_select(options_for_categories, selected: params[:publication][:category]), {prompt: 'All'}, onchange: "$('#filter').submit();" %>
  <% end %>

Would the Ransack gem help with this? GitHub - activerecord-hackery/ransack: Object-based searching.

Hi Joel,

Yes, I encountered the gem, but I don’t use it, because I need very basic filtering functionality. For the publications index view I just need to ability to filter publications on their category. Therefore Ramsack might be overkill.

greetings,

Anthony