本文介紹了按以數(shù)字開頭的字符串排序 - ActiveRecord的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧!
問題描述
限時送ChatGPT賬號..
我正在構(gòu)建 Rails 應(yīng)用程序并嘗試按以數(shù)字開頭的字符串列對數(shù)據(jù)庫中的記錄進(jìn)行排序.
怎么先按號碼下單?
我寧愿按 SQL 順序排序,也不愿按 ruby?? 方法排序.有什么辦法嗎?
I'm building Rails app and trying to order records in database by string column that starts with number.
How can I order by the number at first?
I'd rather ordering as SQL order than sorting by ruby method. Is there any way?
expected order
1.record1
2.record2
10.record10
present order
1.record1
10.record10
2.record2
推薦答案
您可以order by
field + 0
改變field
的數(shù)據(jù)類型code> 隱式轉(zhuǎn)換為一個數(shù)字:
You could order by
field + 0
to change the data type of field
to a number implicitly:
Model.order("field + 0 ASC")
# similar `string`.to_i in Ruby
# `1.record1` => 1
# `10.record10` => 10
這篇關(guān)于按以數(shù)字開頭的字符串排序 - ActiveRecord的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!
【網(wǎng)站聲明】本站部分內(nèi)容來源于互聯(lián)網(wǎng),旨在幫助大家更快的解決問題,如果有圖片或者內(nèi)容侵犯了您的權(quán)益,請聯(lián)系我們刪除處理,感謝您的支持!