Ruby-on-rails 合并两个 ActiveRecord 数组并按 created_at 排序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3593696/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 23:07:00  来源:igfitidea点击:

Merge two ActiveRecord arrays and order by created_at

ruby-on-railsarrayssortingactiverecordmerge

提问by PeterWong

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

By reading from http://guides.rubyonrails.org/layouts_and_rendering.htmlI 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数组进行合并排序?感谢帮助!

回答by zetetic

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

你很亲近。连接数组是用加号完成的:

materials = books + articles

materials = books + articles

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

可以通过调用sort_by方法(混入 from 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 findwith an orderclause, so the database can do the sorting for you.

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

回答by ryancheung

You can also use Array#concatto merge two arrays.

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