开发者

Rails - :order by calculated data

I have multiple instances of data displayed in tables that need to be sorted - much of this data is calculated from the table and isn't just a raw value in the table.

A simple开发者_开发问答 example: Column A = User.visits / User.membership_term

I'm using sortable table columns: http://railscasts.com/episodes/228-sortable-table-columns.

I've tried putting the calculation in the controller and adding a class method to my model but neither seems to work. How can I sort by a calculated field?


You can always use the basic sort method:

irb(main):001:0> a = [1, 2, 3, 4, 5]
=> [1, 2, 3, 4, 5]

irb(main):002:0> a.sort {|d,e| (d - 3).abs <=> (e - 3).abs}
=> [3, 2, 4, 1, 5]    # sort by closest distance away from the number 3

So you can sort your array of active records using similar ways.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜