开发者

Rails: Multiple models records list

开发者 https://www.devze.com 2023-04-13 01:29 出处:网络
How can I show recent added @post and @photos in one list? For examp开发者_JAVA百科le: post - LAlala (10.10.2011)

How can I show recent added @post and @photos in one list? For examp开发者_JAVA百科le:

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!

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号