我想显示一个时间链接混合评论和发布所以我有这个对象
- @posts = Post::all()
- @comments = Comment::all()
如果我这样做
- @post.each ...
- ... end
- @comments.each ...
- ... end
我会得到第一篇文章,然后是评论.但我想要一个时间表,我怎么能创造这个?
我需要结合两个对象来创建一个有序列表,例如:
在帖子中:
- id | name | date
- 1 | post1 | 2015-01-01
- 2 | post2 | 2013-01-01
在评论中:
- id | name | date
- 1 | comment1 | 2014-01-01
- 2 | comment2 | 2016-01-01
如果我这样做
post.each …
comments.each …
结果将是:
- -post1
- -post2
- -comment1
- -comment2
但我需要按日期订购才能获得
- -post2
- -comment1
- -post1
- -comment2
谢谢,对不起我丑陋的英语.
解决方法
帖子和评论是不同的模型(和不同的表),所以我们不能编写sql来获取排序集合,分页等.
通常我在需要混合时间线时使用下一种方法.
我有TimelineItem模型,包含source_id,source_type和timeline_at字段.
- class TimelineItem < ApplicationRecord
- belongs_to :source,polymorphic: true
- end
然后我添加模型逻辑以在需要时创建timeline_item实例:
- has_many :timeline_items,as: :source
- after_create :add_to_timeline
- def add_to_timeline
- timeline_items.create timeline_at: created_at
- end
- TimelineItem.includes(:source).order(:timeline_at).each { |t| pp t.source }