How do you order by a custom model method that has no attribute in SQL?

前端 未结 6 1180
生来不讨喜
生来不讨喜 2021-02-02 08:11

Previously I ordered my posts as this:

@posts = Post.find(:all, :order => \"created_at DESC\")

But now I want to replace created_at

6条回答
  •  無奈伤痛
    2021-02-02 08:47

    It fails because you are asking your db to do the sorting.

    @posts = Post.all.sort {|a,b| a.custom_method <=> b.custom_method}

    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.

提交回复
热议问题