开发者

Sorting Array by ID Number

My database has "spine numbers" and I want to sort by them.

@films = Film.all.sort{|a,b| a.id <=> b.id }

That is my one controller, but the spines go 1, 2, 3开发者_Go百科 ... 100, 101 etc. instead of 001,002,003... so the sorting is out of whack. There's probably an easy class for this something like:

@films = Film.all.sort{|a,b| a.id.abs <=> b.id.abs }

But I don't know it. Thanks for the help.

PS also, why has the rails wiki been down so often recently?


You should use Film.order("id DESC") (or "ASC") method which aplies SQL ORDER BY clause to the query. By default, records are sorted by the primary key column, at least in MySQL.

If this hasn't answered your question, please provide some more information on your database.

Edited Yes, I do see. The only thing that comes to mind is that you're using some kind of string datatype for the spine numbers column. In this case, this kind of sorting makes sense, because values are compared alpabetically char to char like this

1| |
0|5|4
2|5|
1|4|3

which'll return

  • 054
  • 1
  • 143
  • 25

while numeric values such as integer, or float, are compared by their actual value, and not by separate bytes.

So you should create a migration to change the datatype of your spine number to integer.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜