Merge two ActiveRecord arrays and order by created_at

后端 未结 2 1735
误落风尘
误落风尘 2021-01-30 17:17
books = Book.find(:all)
articles = Articles.find(:all)

By reading from http://guides.rubyonrails.org/layouts_and_rendering.html I knew that I could do

相关标签:
2条回答
  • 2021-01-30 17:53

    You can also use Array#concat to merge two arrays.

    0 讨论(0)
  • 2021-01-30 17:55

    You're very close. Concatenating the arrays is done with the plus sign:

    materials = books + articles

    Sorting the combined array can be done by calling the sort_by method (mixed in from Enumerable) and passing in the attribute prefixed with &:

    materials.sort_by(&:created_at)

    This won't be good performance-wise for large result sets. You might consider deriving the Book and Article models from a parent class (like Material) if they are similar, using STI (Single Table Inheritance) to store them in the same table, and using find with an order clause, so the database can do the sorting for you.

    0 讨论(0)
提交回复
热议问题