Find and LIKE 'xxx%' clause


#1

Hi there !

I try to figure out how to do something like this in Rails :

SELECT * FROM my_table WHERE name LIKE ‘GOGONAM%’

My problem is the % and the quotes.
From now, I do like this :

searched_name = params[:name]+’%’
user = MyTable.find(:all, :conditions => [“name LIKE ?”, searched_name])

But is there a more gracefull way to do a LIKE find in ActiveRecord ?

Thanks.


#2

I’d be interested to know that as welll, as your solution is the one I
always see (and use).


#3

As far as i know, there’s no other way of doing it - i’ve had a quick
look through the activerecord source too.

It might be nice to see something like:

MyModel.find(:all, :like => [:name => term])

But i’d question the benefit of it. Things like this can easily get out
of control. Like what if you want to have OR or AND in that like
statement? What if you need to group the like statements? (foo = 1 OR
foo = 2) AND (bar = 3 OR bar = 4).

The fact that active record is quite verbose with it’s sql does mean it
maintains a great deal of flexibility without being over complicated -
the slightly un-graceful result is a small price to pay.

Saying that, it might nice to see a plugin if anyone feels they have
better way. :0)

Steve


#4

On Jun 14, 2006, at 6:02 AM, Stephen B. wrote:

statements? (foo = 1 OR foo = 2) AND (bar = 3 OR bar = 4).

Brian H. wrote:

I’d be interested to know that as welll, as your solution is the
one I always see (and use).
On 6/14/06, Tony < removed_email_address@domain.invalid
mailto:removed_email_address@domain.invalid> wrote:
Hi there !
I try to figure out how to do something like this in Rails :
SELECT * FROM my_table WHERE name LIKE ‘GOGONAM%’
My problem is the % and the quotes.

My ez_where plugin handles this in a nice way IMHO ;) For example:

MyModel.find_where(:all) { name =~ “%#{params[:name]%” }

Is the same as

MyModel.find(:all, :conditions => [“name LIKE ?”, “%#{params[:name]}%”]

I have a new release of the plugin that has many new features for

stuff like this that I will be releasing as soon as I get time to do
a writeup of the new features. For now you can get it like this:

script/plugin install svn://rubyforge.org//var/svn/ez-where

Cheers-
-Ezra


#5

Ezra:

I was waiting to hear from you… I thought that your plugin would
handle it
but I wasn’t sure.

Awesome!


#6

My ez_where plugin handles this in a nice way IMHO :wink: For example:
MyModel.find_where(:all) { name =~ “%#{params[:name]%” }

Excellent :0)

Steve


#7

Ezra Z. wrote:

My ez_where plugin handles this in a nice way IMHO :wink: For example:

Thanks for pointing it ! I’ll try it as soon as possible.