Pet*_*ong 32 arrays sorting merge activerecord ruby-on-rails
books = Book.find(:all)
articles = Articles.find(:all)
Run Code Online (Sandbox Code Playgroud)
通过阅读http://guides.rubyonrails.org/layouts_and_rendering.html, 我知道我可以做类似的事情:
<%= render :partial => [customer1, employee1, customer2, employee2] %>
Run Code Online (Sandbox Code Playgroud)
并且它将适当地使用_customer和_employee部分.
所以我想做那样的事情:
materials = books + articles
materials.sort_by_created_at
Run Code Online (Sandbox Code Playgroud)
并在视图中:
<%= render :partial => materials %>
Run Code Online (Sandbox Code Playgroud)
如何合并和排序两个ActiveRecord阵列???感谢您的帮助!
zet*_*tic 73
你很近.使用加号连接数组:
materials = books + articles
对组合数组进行排序可以通过调用sort_by方法(从中混入Enumerable)并传入前缀为的属性来完成&:
materials.sort_by(&:created_at)
对于大型结果集,这不是很好的性能.如果它们相似,可以考虑从父类(如Material)派生Book和Article模型,使用STI(单表继承)将它们存储在同一个表中,并使用find带order子句,这样数据库就可以进行排序为了你.