Optional mix of filter parameters in a search the Rails way.

Posted by GSP on Stack Overflow See other posts from Stack Overflow or by GSP
Published on 2010-06-02T21:54:09Z Indexed on 2010/06/02 22:24 UTC
Read the original article Hit count: 144

Filed under:

I've got a simple list page with a couple of search filters status which is a simple enumeration and a test query which I want to compare against both the title and description field of my model.

In my controller, I want to do something like this:

def index
  conditions = {}
  conditions[:status] = params[:status] if params[:status] and !params[:status].empty?
  conditions[???] = ["(descr = ? or title = ?)", params[:q], params[:q]] if params[:q] and !params[:q].empty?
  @items = Item.find(:all, :conditions => conditions)
end

Unfortunately, it doesn't look like I can mix the two types of conditions (the hash and the paramatized version). Is there a "Rails Way" of doing this or do I simply have to do something awful like this:

has_status = params[:status] and !params[:status].empty?
has_text = params[:q] and !params[:q].empty?
if has_status and !has_text
   # build paramatized condition with just the status
elsif has_text and !has_status
   # build paramatized condition with just the text query
elsif has_text and has_status
   # build paramatized condition with both
else
   # build paramatized condition with neither
end

I'm migrating from Hibernate and Criteria so forgive me if I'm not thinking of this correctly...

Environment: Rails 2.3.4

© Stack Overflow or respective owner

Related posts about ruby-on-rails