ruby按属性排序不同对象的数组

时间:2017-09-18 12:10:55

标签: ruby

我有不同对象的数组具有相同的属性

class Report1 < ActiveRecord::Base


end
class Report2< ActiveRecord::Base

end
class Report3< ActiveRecord::Base

end

我选择它们是这样的:

@reports1 = Report1 .where(...)
@reports2 = Report2.where(...)
@reports3 = Report3.where(...)

 @reports_all = @reports1 + @reports2 + @reports3

如何按date字段对其进行排序?

我尝试使用.sort但是出现错误,这些对象是不同的类型

3 个答案:

答案 0 :(得分:2)

尝试使用最后处理nil值的sort_by:

@reports_all = @reports_all.sort_by{|report| [report.date ? 0 : 1, report.date]}

答案 1 :(得分:1)

您是否尝试过sort_by

@reports_all = @reports_all.sort_by(&:date)

@reports_all.sort_by!(&:date)

答案 2 :(得分:1)

简而言之,你做错了。直接在数据库中选择和排序:

@reports_all = ActiveBase::Connection.execute(<<-SQL
  (SELECT * FROM report1 WHERE ... 
   UNION
   SELECT * FROM report2 WHERE ... 
   UNION
   SELECT * FROM report3 WHERE ... )
  ORDER BY date
SQL
)