0

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

3 Answers 3

2

Try this sort_by that handles nil values at the end:

@reports_all = @reports_all.sort_by{|report| [report.date ? 0 : 1, report.date]}
Sign up to request clarification or add additional context in comments.

Comments

1

Have you tried sort_by?

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

or

@reports_all.sort_by!(&:date)

3 Comments

`sort_by': comparison of Date with nil failed (ArgumentError)
ok. You have to choose if you want nil dates at the beginning or in the end of the array
let's say in the end
1

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
)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.