Compile data from different models into one list

My app has a user model, as well as multiple other date related models/tables such as anniversaries, holidays, birthdays, and and "other dates" custom model.

I have a user dashboard view that lists them all separately as shown below. How can i display all of these lists as one (call it upcoming events or something) that is listed chronologically and shows them upcoming dates for a certain period of time.

View

*note - These are displayed in a table/list but i stripped html for clarity

    <h1>Holidays</h1>
<% if @user.holidays.any? %>
  <% @user.holidays.each do |hld| %>
    <%= hld.name %>
    <%= hld.date %>
<% end %>

    <h1>Friends Birthdays</h1>
<% if @user.friends.any? %>
  <% @user.friends.each do |frd| %>
      <%= frd.name %>
      <%= frd.dob %>
  <% end %>


    <h1> Anniversary </h1>
<% if @user.anniversaries.any? %>
  <% @user.anniversaries.each do |ann| %>
      <%= ann.spouse_name %>
      <%= ann.anniversary_date %> 
   <% end %>

Thanks!

Models

class User < ActiveRecord::Base
 has_many :friends
 has_many :occasions
 has_many :user_holidays
 has_many :holidays, :through => :user_holidays
 has_many :anniversaries

class Holiday < ActiveRecord::Base
  has_many :user_holidays
  has_many :users, :through => :user_holidays    
end

class Friend < ActiveRecord::Base
  belongs_to :user
end


class Anniversary < ActiveRecord::Base
  belongs_to :user
end

Answers


Assuming you want to be efficient (you could just combine the arrays, sort them and be done with it), there is no direct way to do it through the relations. I am assuming you have an events model which has a foreign key to the user, in that case,

Events.where(:user_id => @user.id).where(<EVENT DATE FILTERS>).order("event_date DESC")

-- EDIT --

This is quite dirty, but I cant think of any other direct db way of accomplishing this.

events = @user.holidays.map{|h| [h.name, h.date, :holiday]} + \
         @user.friends.map{|f| [f.name, f.dob, :birthday]} + \
         @user.anniversaries.map{|a| [a.spouse_name, a.anniversary.date, :anniversary]}
events.map!{|event| {:name => event[0], :date => event[1], :event_type => event[2]}}
# You now have an array of hashes with the events name, date and type.

events.sort{|a, b| a[:date] <=> b[:date]}  # sort / filter

Need Your Help

$resource relations in Angular.js [updated]

angularjs

I'm trying to figure out the best way to write a model that relates to other models, such as an Order that has 1 or more OrderItems.

How to grab a field name's value in a CURL response

php string parsing curl

I first want to say I'm a beginner with PHP and my code is definitely not efficient to say the least.