Generic Rails Search

Once again, I’m not involved enough in the rails community to know if something like this has already been done, but I thought it was kind of cool. It’s a generic search system for ActiveRecords:

def searcher_find(paramname, model)
  conds = []
  condvals = []
  columns = model.column_names
  params[paramname].each do |k, v|
    ks = k.to_s
    if columns.include? ks

      col = model.columns_hash[ks]
      case col.type
      when :text
        conds << " #{k} like ? "
        condvals << "%#{v}%"
      when :integer
        if v != ""
          conds << " #{k} = ? "
          condvals << v.to_i
      when :float
        if v != ""
          conds << " #{k} = ? "
          condvals << v == v.to_f


  return model.find(:all, :conditions => [conds.join(' and '), *condvals])

You would call it like so: @products = searcher_find(:product, Product). The above version is just the “simplest thing that could possibly work”, and probably needs fixing, but I thought I’d write it down so that others could take it and use it.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s