您如何通过在 SQL 中没有属性的自定义模型方法进行排序? [英] How do you order by a custom model method that has no attribute in SQL?
本文介绍了您如何通过在 SQL 中没有属性的自定义模型方法进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
以前我这样订购我的帖子:
Previously I ordered my posts as this:
@posts = Post.find(:all, :order => "created_at DESC")
但现在我想用我在 Post 模型中编写的自定义方法替换 created_at
,该方法给出一个数字作为结果.
But now I want to replace created_at
with a custom method I wrote in the Post model that gives a number as its result.
我的猜测:
@posts = Post.find(:all, :order => "custom_method DESC")
失败了..
推荐答案
它失败了,因为您要求您的数据库进行排序.
It fails because you are asking your db to do the sorting.
@posts = Post.all.sort {|a,b|a.custom_method <=>b.custom_method}
请注意,当您想要开始分页结果并且不再希望获取 .all
时,这变得非常重要.在开始之前先考虑一下您的设计.
Note that this becomes non-trivial when you want to start paging results and no longer wish to fetch .all
. Think about your design a bit before you go with this.
这篇关于您如何通过在 SQL 中没有属性的自定义模型方法进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文