合并两个查询的结果并按 created_at 排序?[轨道3] [英] combine results from two queries and order by created_at? [rails 3]
本文介绍了合并两个查询的结果并按 created_at 排序?[轨道3]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
寻找一种简单的方法,利用活动记录从两个模型中抓取数据,合并数据,然后通过created_at对合并的输出进行排序.
Looking for a simple method utilizing active record to grab data from two models, combine the data, and then sort the combined output by created_at.
例如:
假设有两个模型,Comment &都喜欢belongs_to用户
assume two models, Comment & Like both belongs_to User
返回按日期排序的@user 评论和喜欢的组合列表
return a combined list of @user's comments and likes sorted by date
我知道我可以在 SQL 中做到这一点,但我真的很想要一个活动记录解决方案.
I know I can do this in SQL but I'd really like an active record solution.
谢谢!
推荐答案
我认为应该这么简单:
combined_sorted = (User.comments + User.likes).sort{|a,b| a.created_at <=> b.created_at }
这篇关于合并两个查询的结果并按 created_at 排序?[轨道3]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文