简体   繁体   English

Rails:多个模型记录列表

[英]Rails: Multiple models records list

How can I show recent added @post and @photos in one list? 如何在一个列表中显示最近添加的@post和@photos? 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: 或者,使用group_by执行此操作:

@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. 如果我是DRYer代码,我会将视图逻辑移动到帮助器中。

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). 创建一个数据库视图,其中包含PostPhoto所需的列,包括包含模型名称的“ type ”列(您需要多态性的列)。 Call this view for example " list_items ". 将此视图称为list_items ”。 Then create a model called " ListItem ". 然后创建一个名为“ 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. 但是,使用可列表的 gem更容易实现所有这些。 Check it out! 看看这个!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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