I have 2 models that I am interested in merging and then ordering them by the created_at column. One of the models is photos and the other one is statuses. Currently, I have two tabs, photos and statuses in which I display each of the model data sepeartely by the time they were created. However, I want to make another tab called photos and statuses, and display them together. My question is how can I display both of them by the time they were created together. For example I would like it to have an order sort of like this
Hell World (status posted 4 hours ago)
<img src="blah/blah" /> (posted 6 hours ago)
Hello (stat开发者_StackOverflowus posted 8 hours ago)
Any suggestions? Thanks in advance
There's probably some slick way to do this in SQL but if you're only displaying a few records, doing it in Ruby is fine, and readable. Something like:
@photos = Photo.recent(5)
@images = Image.recent(5)
@both = (@photos + @images).sort_by(&:created_at).reverse
If your goal is to display a classic activity feed, I recommend the timeline_fu plugin:
https://github.com/jamesgolick/timeline_fu
Very easy to set up, pretty slick.
You can simply add both to an array, then sort:
@merged = (@statuses.all + @photos.all).sort_by! {|o| o.created_at }
精彩评论