combine results from two queries and order by created_at? [rails 3]

前端 未结 2 552
北荒
北荒 2020-12-14 19:30

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.

For example:

相关标签:
2条回答
  • 2020-12-14 19:49

    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

    0 讨论(0)
  • 2020-12-14 19:57

    I believe it should be as simple as:

    combined_sorted = (User.comments + User.likes).sort{|a,b| a.created_at <=> b.created_at }
    
    0 讨论(0)
提交回复
热议问题