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

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

    This is a bit more complicated than what I like but this I like to keep my sort to stay as a active record model so its bit more complicated than just

    Post.all.sort_by {|post| post.custom_method }
    

    what I do is:

    ids = Post.all.sort_by {|post| post.custom_method }.map(&:ids)
    Post.for_ids_with_order(ids)
    

    this is a custom scope in the Post model

    #app/models/post.rb
    class Post < ApplicationRecord
      ...
        scope :for_ids_with_order, ->(ids) {
        order = sanitize_sql_array(
          ["position(id::text in ?)", ids.join(',')]
        )
        where(:id => ids).order(order)
      }
    
      ...
    end
    

    I hope that this help

提交回复
热议问题