Searching multiple fields with conditions

I am very new at RoR but am trying to tweak the code for the AJAX table
from How to paginate, sort and search a table with Ajax and Rails · dev.nozav.org.

I have it all working the way I want except for one line of code:

conditions = [“firstname LIKE ?” , “%#{@params[:query]}%”] unless
@params[:query].nil?

I need this to look at multiple fields not just firstname. Any idea how
I do this?

On May 23, 2007, at 2:56 PM, Heather White wrote:

conditions = [“firstname LIKE ?” , “%#{@params[:query]}%”] unless
@params[:query].nil?

I need this to look at multiple fields not just firstname. Any
idea how
I do this?

were you just doing = comparisons then you could extract a hash of
conditions from the params and pass that directly. for what you’re
doing you might look at using the ez_where plugin:

http://opensvn.csie.org/ezra/rails/plugins/dev/ez_where/

-faisal

I am very new at RoR but am trying to tweak the code for the AJAX table
from How to paginate, sort and search a table with Ajax and Rails · dev.nozav.org.

I have it all working the way I want except for one line of code:

conditions = [“firstname LIKE ?” , “%#{@params[:query]}%”] unless
@params[:query].nil?

I need this to look at multiple fields not just firstname. Any idea how
I do this?

unless params[:query].blank?
query = “%#{@params[:query]}%”
conditions = [“firstname LIKE ? OR lastname LIKE ?”, query, query]
end

You can add as many OR’s as you want as long as you keep adding more
query’s to the end.

Your database may not like you if you do this, but that’s another matter
:slight_smile:

-philip

Also check out ActiveRecord::Extensions for more hash-based conditions
suck as field_like, field_contains, field_lt, field_gt, field_ne, etc.
(http://www.continuousthinking.com/tags/arext).

However, hash-based conditions are added together with AND rather than
OR, so it’s not much use for this particular prooblem.

Philip H. wrote:

unless params[:query].blank?
query = “%#{@params[:query]}%”
conditions = [“firstname LIKE ? OR lastname LIKE ?”, query, query]
end

Thanks that did exactly what I needed.

I am just about to release 0.7.0 for ActiveRecord::Extensions. I am
thinking of including OR functionality. Please email me privately if
you have comments or suggestions on this.

I am planning to have:
Book.find :all, :conditions=>{ :name_like => “Star
Wars”, :or_name_like=>“Star Trek” }

generate SQL like:
name LIKE "Star Wars"OR name LIKE “Star Trek”

It’s limitation is that it will not be able to group OR’d selectors,
but it provides basic OR capabilities. thought?

Zach
http://www.continuousthinking.com