SearchLogic Just Seems … Logical …

I hate searching records. It drives me insane to build up crazy conditions to pass to ActiveRecord. I’ve used numerous plugins, but they’re either all clunky, lack certain search functionality, or flat out don’t work well. I was happy to hear about the new SearchLogic gem for searching records. I decided today, being Friday and all, that I would take some time to investigate it.

The idea of chaining is common, but what caught my attention is passing a hash of search criteria to search. In my situation, I wanted to test out filtering by state, since I use rubyist-aasm, as well as filtering by letter.

Here is the HAML view.

1
2
3
4
5
6
7
8
9
10
11
12
%p Filter results by:
%p
  State:
  = link_to 'All', admin_users_path
  == | #{link_to 'Active', admin_users_path(:state => :active)}
  == | #{link_to 'Inactive', admin_users_path(:state => :inactive)}
 
%p
  Login:
  = link_to 'All', admin_users_path
  - ("A".."Z").to_a.each do |l|
    == | #{link_to l, admin_users_path(:l => l)}

Now is the best part, the index action for the Users controller, with will_paginate plugged in:

1
2
3
4
5
6
7
def index
    opts = {}
    opts[:login_begins_with] = params[:l] if params[:l]
    opts[:state_equals] = params[:state] if params[:state]
    @search = User.search(opts)
    @users = @search.paginate(:page => params[:page], :per_page => 25)
  end

It has dynamic finders, plugs in with your current named_scopes and more; It doesn’t get much simpler than this.

Related Posts

  1. Inherited_resources is as close to GOD as you can get
  2. Paperclip Resized Image Details In to_xml
  3. Canonical URL tag, RubyOnRails, and why you are stupid for not using it
  4. Nifty RubyOnRails Layout Method
  5. RubyOnRails Route Generation Awesomeness
General, Git, Programming, RubyOnRails

If you enjoyed this post, please consider to leave a comment or subscribe to the feed and get future articles delivered to your feed reader.

blog comments powered by Disqus