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

前端 未结 6 1121
生来不讨喜
生来不讨喜 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:58

    Well, just Post.find(:all) would return an array of AR objects. So you could use Array.sort_by and pass it a block, and since those records are already fetched, you can access the virtual attribute inside the block that sort_by takes.

    RDoc: Enumerable.sort_by

提交回复
热议问题