Hello, all my fellow coders! I've got a problem ohh chok!.. :P Now my problem i that i'm trying to make a design for a bigger site, it's going good. Until i should make the content/news slider. It should take data from multiple tables and returning to the application.html.erb.
So it is take reviews and announcements just the latest 5 and order it af开发者_JS百科ter latest created. and then give it to me in the application.html.erb.. (Rails 3.0.0.beta4)
hope you guys understands me.
Take the latest 5 for all the models, then put all records on an array, sort the array and take the first 5 elements.
# consider moving .order('date desc').limit(5) to a named scope or a module
announcements = Announcement.order('date desc').limit(5)
posts = Post.order('date desc').limit(5)
monkeys = Monkey.order('date desc').limit(5)
# .. add others here
elements = (announcements + posts + monkeys).sort_by(&:date).reverse[1..5]
The variable elements
will have the 5, if they exist.
Note: I'm assuming that all your models have a method called "date". You can change it to date_created or whatever.
You can put this code on several places, but I think the best one would be a "home" controller, created specifically for rendering the home page. The elements would be calculated on its show action.
don't know if it's more performant to use this syntax, instead of the one from egarcia:
elements = (announcements | posts | monkeys).sort_by(&:date).reverse[1..5]
if you need to use this code in several pages (for example in sidebars), then the best way could be to write an helper (say: last_items)
精彩评论