I have three models: paste
, snippet
and tutorial
. I want to show the newest of all of them mixed in one list, like this on the page:
<ul>
<li>Just a paste</li>
<li>The worst snippet ever (-10202343 kudos) (1 quadrillion comments)</li>
<li>Just another paste</li>
<li>Ruby on Rails tutorial (5 kudos) (2 comments)</li>
<li>Another snippet</li>
</ul>
Ordered by date. The problem is that I want to mix thes开发者_开发知识库e three models in one list. All models have specific attributes (e.g. snippet
and tutorial
have tags, all have titles, tutorial
s and snippet
s have have kudos, only paste
has a private boolean (so it should not be listed)).
How can I do some kind of mixing these different models in my view? Thanks
I would solve this at the database-level, introducing a PublishedItem, and the PublishedItem then points to either a Paste, a Snippet or a Tutorial. That would solve creating the list of items: just select the 5 latest published items. And from a published item you can then find the correct item, and show it.
Grab a list of the "events" or whatever in your controller
@events = Paste.find_all
@events << Snippet.find(:order => "votes", :limit => 1)
@events << Tutorial.find_all
then in your view
<%
@events.each do |event|
display_snippet(event) if event.class == Snippet
display_tutorial(event) if event.class == Tutorial
end
%>
there are a few ways to handle the view part of it, but it seems pretty straight forward. In this example, display_snippet and display_event would be helper methods but it might be cleaner to use partials.
精彩评论