Monday, February 4, 2008

a Ruby on Rails query with the LIKE syntax in :conditions

[ This is working on Rails 2.0.2 in Aptana Studio 1.1.0.007007 with RadRails plugin 0.9.3.6479 ]

In most rails apps, you would do either a simple .find(:all) or .find(:id) or .find(params[:id]). I needed to query my database based on a simple condition, matching all words in a column that starts with a particular alphabet.

select * from mytable where username LIKE a%;
(would return all usernames that start with a, like adrian, avin, etc).

To do that in RoR, I needed to add a :condition to the default query.

However, tagging it this way didn't help
:condition => 'username LIKE #{params[:uname]}%',
the sanitizer would convert that to username LIKE 'a'%, which gives an SQL exception.

After searching the web, scanning dozens of sites, including the rails API, the RoR forum, I accidentally stumbled upon the solution in the comments section of a blog (I can't remember where it was now, sorry).

My query is subsequently modified and tested to be

@results = User.find(:all, :conditions => ['username LIKE ?', params[:uname]+'%' ])

Sorry if this was an obvious thing to a lot of other people... :P

2 comments:

Rimu said...

ugh. pity there isn't a nicer way :)

xQ said...

Yup.. it's very messy if you have nested sql statements, it could've been more elegant... maybe that will happen in ruby v2 or v3 :D :P