Rails Like SQL

If you have played with Ruby on Rails you may already be familiar with the ActiveRecord’s find method. Here is a recap, say I have a Item model:

class Item < ActiveRecord::Base
end

In your controller you can use the Item class to find all items that meet a given criteria. Here are some examples:

# Find the lowest priced item
lowest = Item.find(:first, :order => 'price asc')
# Find all items by category
items = Item.find(:all, :conditions => ["category = ?", params[:category])

What I couldn’t fine anywhere is, how to use the ActiveRecord’s find method to find items whose name is like a given parameter. In SQL I could do something like this:

select * from items where name like 'ItemName%';

My first attempt at solving this left me open to hacks via SQL injection. After some thought it occurred to me that I could do the following:

like = params[:name].concat("%")
items = Item.find(:all, :conditions => ["name like ?", like])

I still haven’t found the official way to accomplish the above but in the mean time this gets the job done.

Technorati Tags: , , , ,