2014-10-30 52 views
0

所以我有一个表列priority_n。假设该表中有5个项目。其中两个优先级为n,其余三个优先级为n。按两列栏排序,但如果栏位为零,则优先排列栏位?

所以我想做一个where(priority_n:nil).order(published_at::desc)与where.not(priority_n:nil).order(priority_n::asc)结合使用。因此,我希望在活动记录关系开始的时候没有记录的关键字,然后是优先关键记录关系。有没有办法做到这一点?

回答

0

我认为这将这样的伎俩:现在

class MyModel 

    scope :with_priority, -> { where.not(priority: nil).reorder(:priority) } 
    scope :without_priority, -> { where(priority: nil).reorder(published_at: :desc) } 

    def self.special_order 
    without_priority.to_a + with_priority.to_a 
    end 
end 

,您可以拨打:MyModel.special_order返回数组排序喜欢你问。