【问题标题】:Merge two ActiveRecord arrays and order by created_at合并两个 ActiveRecord 数组并按 created_at 排序
【发布时间】:2011-04-05 08:30:57
【问题描述】:
books = Book.find(:all)
articles = Articles.find(:all)

通过阅读http://guides.rubyonrails.org/layouts_and_rendering.html 我知道我可以这样做:

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

它会酌情使用 _customer 和 _employee 部分。

所以我想做这样的事情:

materials = books + articles
materials.sort_by_created_at

在视图中:

<%= render :partial => materials %>

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

【问题讨论】:

    标签: ruby-on-rails arrays sorting activerecord merge


    【解决方案1】:

    你很亲密。使用加号连接数组:

    materials = books + articles

    可以通过调用sort_by方法(从Enumerable混入)并传入以&amp;:为前缀的属性来对组合数组进行排序

    materials.sort_by(&amp;:created_at)

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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 2020-11-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-10-03
        • 1970-01-01
        • 2018-04-22
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多