Reputation: 9627
I have array of different object with the same properties
class Report1 < ActiveRecord::Base
end
class Report2< ActiveRecord::Base
end
class Report3< ActiveRecord::Base
end
And I select them like this:
@reports1 = Report1 .where(...)
@reports2 = Report2.where(...)
@reports3 = Report3.where(...)
@reports_all = @reports1 + @reports2 + @reports3
How do I sort it by date
field?
I tried to use .sort but got an error that these objects are different types
Upvotes: 0
Views: 63
Reputation: 121000
You are doing it wrong in a nutshell. Select and sort directly in the database:
@reports_all = ActiveBase::Connection.execute(<<-SQL
(SELECT * FROM report1 WHERE ...
UNION
SELECT * FROM report2 WHERE ...
UNION
SELECT * FROM report3 WHERE ... )
ORDER BY date
SQL
)
Upvotes: 1
Reputation: 534
Try this sort_by that handles nil values at the end:
@reports_all = @reports_all.sort_by{|report| [report.date ? 0 : 1, report.date]}
Upvotes: 2
Reputation: 30056
Have you tried sort_by
?
@reports_all = @reports_all.sort_by(&:date)
or
@reports_all.sort_by!(&:date)
Upvotes: 1