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
        end
      when :float
        if v != ""
          conds << " #{k} = ? "
          condvals << v == v.to_f
        end
      end

    end
  end

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

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:

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s