0

I have a homepage view in my rails app and I also have two types of content, articles and events. I'd like to have a partial on the homepage that displays the most recent articles and events together (mixed, like a news feed). Articles should be sorted by created_at and events should be sorted by start_date together.

My question is how do I create a single partial to show the two types of content arrays in a single array and sort them both properly? Do I create a method and place it in the home_controller to do this?

Thanks

2 Answers2

0

This is how you merge results and a rough implementation of a custom search. I haven't tested the search so no guarantees it works.

@events   = Events.all
@articles = Articles.all

@events_and_articles = (@events + @articles).sort { |a, b|
  a_value = a.is_a?(Event) ? a.start_date : a.created_at 
  b_value = b.is_a?(Event) ? b.start_date : b.created_at

  a_value <=> b_value
}
Dan Grahn
  • 9,044
  • 4
  • 37
  • 74
  • Would you place this in the homepage controller? How would the actual array to return the content look like? – Arash Hadipanah Jul 16 '13 at 23:51
  • Yes you would place it in the homepage controller. It would be a structure of ActiveRecord instances sorted by the start and created at dates. – Dan Grahn Jul 17 '13 at 10:49
0

This might not be the most efficient, but I tested it and it works.

def getstuff
    stuff = Array.new
    #Get the 10 most recent articles and add them to an array.
    Article.order("created_at DESC").limit(10).each do |item|
        stuff.push(item)
    end
    #Add the 10 most recent events to the same array
    Event.order("start_date DESC").limit(10).each do |item|
        stuff.push(item)
    end
    #Sort the array by the correct value based on the class.
    stuff.sort_by! { |item| 
        item.class.name.eql?("Article") ? item["created_at"] : item["start_date"]
     }
    #Return the reverse of the sort result for the correct order.
    return stuff.reverse!
end
Sean Ryan
  • 438
  • 4
  • 11
  • I was testing this one, I placed the code in my homepage controller. This is what I have in the partial but it returns an error `<% getstuff.each do |stuff| %> <%= stuff.title %> <% end %>` The error that's returned is `undefined local variable or method `getstuff' for #<#:0x007ff05b3f2ef8>` – Arash Hadipanah Jul 17 '13 at 14:06