Rails Like SQL

11
May
2

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: , , , ,

Enjoy. Share. Be Happy.
  • Digg
  • del.icio.us
  • Facebook
  • Mixx
  • Google
  • BlinkList
  • MySpace
  • Netvouz
  • NewsVine
  • StumbleUpon
  • TwitThis
Filed under: Ruby, SQL, TechKnow
2 Comments

2 Comments

  1. Steven
    2:51 pm on March 31st, 2007

    Why not just use find_by_sql() ?

  2. John
    1:26 pm on September 10th, 2007

    I had the same problem. Here’s the answer:

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

Leave a comment

RSS feed for comments on this post