How to select rows that start with a digit in Rails?

I have page that shows items in an index.

I'm able to get items by letter using the following:

scope :by_letter, lambda { |letter| where("name LIKE '#{letter}%'") }

But I can't figure out an elegant solution for names that start with a number (0-9).

How could I rewrite this or a separate scope that would let me search for names starting with a digit?

EDIT: I'm trying to get all rows that start with 0-9 in one go (not separately for each number).

Answers


this should work

scope :starts_with_number, where("name REGEXP '[0-9]%'")

Jacob, try this slightly rewritten version of what you ended up with:

@letter_merchants = (0..9).map { |d| Merchant.by_letter(d) }

Please note that this should only illustrate how awesome language Ruby is, not how the problem should be solved (there would be too many database calls).


Here's how I ended up doing it:

@letter_merchants = []
(0..9).to_a.each do |digit|
  @letter_merchants |= Merchant.by_letter(digit)
end

One disadvantage of REGEXP is that it can't use indexes. however

scope :starts_with_number, where("name >= '0' and name < ':')

can use an index on name. It does rely on the characters 0-9: being in precisely that order, with nothing in between which will be the case in anything like ascii, utf8 but not if you used ebcdic or anything crazy like that


Need Your Help

Play YUV video on Android

android bitmap android-canvas yuv

I want to show the YUV video on the android

Saving a cache object when a WCF webservice is ended

c# wcf web-services

I have a simple WCF webservice with 2 methods : one save/updates an obect in the cache and the other one deletes it. How can I save the object when I close the webservice server.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.