Easy newbie question: find conditions

Hello!

I am trying to run a simple find, and don't know how to do it. I'm essentially creating a glossary, and I want to be able to find all the words that begin with each letter.

Seems like I ought to be able to do something like this:

Word.find(:all, :conditions => ['spelling=?', 'a*'])

But that doesn't work... How do a find all the records where the spelling begins with 'a'?

You'll need a LIKE clause:

Work.find :all, :conditions => ['spelling LIKE ?', 'a%']

Note also that SQL uses % instead of *.

Jeff

REST with Rails, Oct 4, 2008 in Austin, TX: http://www.purpleworkshops.com/workshops/rest-and-web-services

softiesonrails.com - blog purpleworkshops.com - training pragprog.com/titles/cerailn - Upcoming book, Rails for .NET Developers

Excellent, thank you!

Hello!

I am trying to run a simple find, and don't know how to do it. I'm essentially creating a glossary, and I want to be able to find all the words that begin with each letter.

Seems like I ought to be able to do something like this:

Word.find(:all, :conditions => ['spelling=?', 'a*'])

But that doesn't work... How do a find all the records where the spelling begins with 'a'?

As a further addendum, what if I wanted to find all words that begin with 'a' and 'b' in one query?

If it helps, I'm using sqlite3.

Probably something like this:

Work.find :all, :conditions => ['spelling LIKE ? OR spelling LIKE ?', 'a%', 'b%']

My SQL-fu isn't great so there might be a better way to do it.

Jeff

REST with Rails, Oct 4, 2008 in Austin, TX: http://www.purpleworkshops.com/workshops/rest-and-web-services

softiesonrails.com - blog purpleworkshops.com - training pragprog.com/titles/cerailn - Upcoming book, Rails for .NET Developers

Probably something like this:

Work.find :all, :conditions => ['spelling LIKE ? OR spelling LIKE ?', 'a%', 'b%']

Nope, that doesn't seem to do it....

I, too, am using sqlite3 and this works for me:

Video.find(:all, :conditions=>['title LIKE ? OR title LIKE ?', 'a%', 'b%'])

=> [#<Video id: 3, title: "a", added_by: nil, created_at: "2008-08-11 21:05:32", updated_at: "2008-08-11 21:05:32">, #<Video id: 4, title: "b", added_by: nil, created_at: "2008-08-11 21:05:38", updated_at: "2008-08-11 21:05:38">]

Morgan Kay wrote:

Lake Denman wrote:

I, too, am using sqlite3 and this works for me:

Video.find(:all, :conditions=>['title LIKE ? OR title LIKE ?', 'a%', 'b%'])

=> [#<Video id: 3, title: "a", added_by: nil, created_at: "2008-08-11 21:05:32", updated_at: "2008-08-11 21:05:32">, #<Video id: 4, title: "b", added_by: nil, created_at: "2008-08-11 21:05:38", updated_at: "2008-08-11 21:05:38">]

That does the trick, thank you!