通过created_at组合来自两个查询和订单的结果?(rails 3)

时间:2022-01-29 12:13:20

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.

寻找一种使用活动记录从两个模型获取数据的简单方法,结合数据,然后使用created_at对组合输出进行排序。

For example:

例如:

assume two models, Comment & Like both belongs_to User

假设有两个模型,comments & Like both belongs_to User

return a combined list of @user's comments and likes sorted by date

返回根据日期排序的@user注释和like的组合列表

I know I can do this in SQL but I'd really like an active record solution.

我知道我可以在SQL中这样做,但我真的想要一个活动记录解决方案。

Thanks!

谢谢!

2 个解决方案

#1


21  

I believe it should be as simple as:

我认为应该这么简单:

combined_sorted = (User.comments + User.likes).sort{|a,b| a.created_at <=> b.created_at }

#2


0  

How about something like (untested):

比如(未经测试的):

class User < ActiveRecord::Base
  scope :activities_by_date, :joins(:comments).joins(:likes).order("created_at desc")
end

Then you can do @user.activities_by_date and let the db do all the work

然后你可以做@user。activities_by_date并让db完成所有的工作

#1


21  

I believe it should be as simple as:

我认为应该这么简单:

combined_sorted = (User.comments + User.likes).sort{|a,b| a.created_at <=> b.created_at }

#2


0  

How about something like (untested):

比如(未经测试的):

class User < ActiveRecord::Base
  scope :activities_by_date, :joins(:comments).joins(:likes).order("created_at desc")
end

Then you can do @user.activities_by_date and let the db do all the work

然后你可以做@user。activities_by_date并让db完成所有的工作