简体   繁体   中英

Rails: Multiple models records list

How can I show recent added @post and @photos in one list? For example:

post - LAlala (10.10.2011)
photos - [] [] [] [] (1.1.2011)
post - Bbbdsfbs (2.12.2010)
post - Lasdasdf2 (2.10.2009)
@posts = Post.limit(20).order('created_at desc')
@photos = Photo.limit(20).order('created_at desc')
@recent_items = (@posts + @photos).sort_by(&:created_at)

<% @recent_items.each do |item| %>
  <% if item.class == "Photo" %>
    <%= image_tag item.url %>
  <% else %>
    <%= item.title %>
  <% end %>
<% end %>

Alternatively, use group_by to do it like this:

@recent_items = (@posts + @photos).group_by(&:created_at)

<% @recent_items.each do |date, items| %>
    Date: <%= date %>
    <% items.each do |item| %>
      Show information here.
    <% end %>
<% end >

I would move the view logic into a helper if I were you for DRYer code.

It is much better to do this is the database.

I just say this: polymorphism + database views.

Create a database view which contains the columns you need from both Post and Photo , including the column " type " containing a the name of the model (you need it for the polymorphism). Call this view for example " list_items ". Then create a model called " ListItem ". Then you can use this model like any other, paginate it and whatever you need to do.

ListItem.order("created_at > ?", Date.yesterday).page(params[:page])

And don't forget to configure the polymorphic association

However, all this is much easier to accomplish with the listable gem. Check it out!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM