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

Related posts:

  1. High Rolling With Rails
  2. Acts As Taggable Conditions Hack
  3. JDBC and SQL Server 2005
  4. Creating Custom Rails Routes
  5. Desc SQL Tables

This entry was posted in Ruby, SQL, TechKnow. Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

4 Comments

  1. Steven
    Posted March 31, 2007 at 2:51 pm | Permalink

    Why not just use find_by_sql() ?

  2. John
    Posted September 10, 2007 at 1:26 pm | Permalink

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

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

  3. marco
    Posted July 27, 2010 at 11:27 am | Permalink

    Hi! I finally got it, here is what I did:
    like= “%”.concat(params[:name].concat(“%”))
    @items=Item.find(:all, :conditions => ["name like ?",like])

  4. Posted September 29, 2011 at 2:20 pm | Permalink

    Remember rails finder methods with conditions are deprecated in 3.1 and will be removed in 3.2 so the proper way of doing something like this would be to use find_by_sql, at least while a DB agnostic method comes up that does the LIKE job

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*