简体   繁体   中英

What is the simplest way to order results from a SQL query on part of a string field in Rails?

Consider a table with a text field with the following form:

"foo,bar"

EDITS: "bar" is the first string after the comma. There is only one comma.

What is the simplest way to order by bar ? It can be in either SQL (PostgreSQL) or Ruby.

MyTable.all.sort_by { |r| r.my_text.match(/,(.*)$/)[1] }

You can do it inside the database like this:

M.order("substring(c from ',.*$')")

where M is your model and c is the column in question. The substring call leaves the comma in the substring but that won't alter the sorting and comparing the commas during sorting will probably be faster than trying to remove them. Also, that form of PostgreSQL's substring should work in 8.2 so it should work with a Heroku shared database.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM