合并两个ActiveRecord数组并按created_at排序 [英] Merge two ActiveRecord arrays and order by created_at

查看:68
本文介绍了合并两个ActiveRecord数组并按created_at排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

books = Book.find(:all)
articles = Articles.find(:all)

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

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

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

,它将适当地使用_customer和_employee局部.

and it would use _customer and _employee partials as appropriate.

所以我想做这样的事情:

So I want to do something like that:

materials = books + articles
materials.sort_by_created_at

并在视图中:

<%= render :partial => materials %>

如何对两个ActiveRecord数组进行合并和排序?谢谢!!

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

推荐答案

您非常亲密.连接数组使用加号完成:

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

materials = books + articles

可以通过调用sort_by方法(从Enumerable混合)并传递以&:

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)

这对于大型结果集而言并不是很好的性能.您可能会考虑从父类(例如Material)相似的Book和Article模型,如果它们相似,则使用STI(单表继承)将它们存储在同一表中,并使用findorder子句,因此数据库可以为您进行排序.

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.

这篇关于合并两个ActiveRecord数组并按created_at排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆