开发者

In Active Record, how can I search for titles that start with an integer?

I am using a Postgres backend but it could in theory change to MySQL (or even, yes, MS SQL) 开发者_JS百科so I'm looking for a generic example that works.

Say I have a column labeled "title" that contains video game titles. If I want to query all of the ones that start with a number then I use:

Games.where("title LIKE '0%' OR title LIKE '1%' OR title LIKE '2%' OR title LIKE '3%' OR title LIKE '4%' OR title LIKE '5%' OR title LIKE '6%' OR title LIKE '7%' OR title LIKE '8%' OR title LIKE '9%'")

This certainly works and it will probably work across any RDMS but looks a little ugly. Is there a better way using Rails/AR 3?

Thanks!


Use the powerful regular expressions.

Games.where("title REGEXP ?","^\\d")

More information: here

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜