通过created_at合并两个ActiveRecord数组和order

时间:2022-06-11 08:18: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 something like:

通过阅读http://guides.rubyonrails.org/layouts_and_rendering.html,我知道我可以做一些类似的事情:

<%= render :partial => [customer1, employee1, customer2, employee2] %>

and it would use _customer and _employee partials as appropriate.

它将适当地使用_customer和_employee部分。

So I want to do something like that:

所以我想做这样的事情:

materials = books + articles
materials.sort_by_created_at

and in the view:

和观点:

<%= render :partial => materials %>

How to do the merging and sorting of two ActiveRecord arrays???Thanks for help!

如何合并和排序两个ActiveRecord阵列?谢谢你的帮助!

2 个解决方案

#1


72  

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 &:

对组合数组进行排序可以通过调用sort_by方法(混合来自Enumerable)并传入以&开头的属性来完成:

materials.sort_by(&:created_at)

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.

对于大型结果集来说,这不是很好的性能。您可以考虑从父类(如Material)派生图书和文章模型(如果它们相似),使用STI(单表继承)将它们存储在同一个表中,并使用find和order子句,以便数据库为您进行排序。

#2


6  

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

您还可以使用Array#concat来合并两个数组。

#1


72  

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 &:

对组合数组进行排序可以通过调用sort_by方法(混合来自Enumerable)并传入以&开头的属性来完成:

materials.sort_by(&:created_at)

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.

对于大型结果集来说,这不是很好的性能。您可以考虑从父类(如Material)派生图书和文章模型(如果它们相似),使用STI(单表继承)将它们存储在同一个表中,并使用find和order子句,以便数据库为您进行排序。

#2


6  

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

您还可以使用Array#concat来合并两个数组。