Rails: searchlogic search with or conditions
Asked Answered
K

1

6

I'm using the 'binarylogic-searchlogic' gem in version 2.3.5 along with Rails 2.3.4.

What I want to do is performing a search on a model for a specified value over multiple attributes. I achieve this through chaining everything together like

User.first_name_or_last_name_or_email_like(value)

But with more and more attributes in this search this tends to be ugly. Instead I'd like to use the search mechanism of searchlogic like this:

search = User.search
search.first_name_like = value
search.last_name_like  = value
..
@users = search.all

So this is the way to search via AND - but what I want is OR. I've found two ways to achieve this, but both don't work.

1st one: prepend an or_ to the condition

search = User.search
search.first_name_like = value
search.or_last_name_like  = value
@users = search.all

This gives me The or_last_name_like is not a valid condition. You may only use conditions that map to a named scope

2nd one: use search.any

search = User.search
search.first_name_like = value
search.last_name_like  = value
@users = search.any

gives me undefined methodany' for #`.

Any idea's on that? Am I mising the right point of the readme?

Thanks for your very welcome help!

edit: time for some ugly workaround:

search = User.search
search.first_name_like = value
search.last_name_like  = value
User.find(:all, :conditions => search.scope(:find).gsub('AND','OR'))

Works but is surely not the way to go, isn't it?

Ku answered 3/11, 2009 at 10:11 Comment(0)
F
2

I don't think there's another way of doing it. By default it will join the arguments with AND.

The OR code, only seems to work with chaining.

Forbes answered 4/11, 2009 at 15:18 Comment(1)
+1 After a quick look, I agree with this answer. For confirmation, you can ask the Searchlogic mailing list.Panchito

© 2022 - 2024 — McMap. All rights reserved.