ruby-on-rails – 组合2个物体和排序轨道5

前端之家收集整理的这篇文章主要介绍了ruby-on-rails – 组合2个物体和排序轨道5前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想显示一个时间链接混合评论和发布所以我有这个对象
  1. @posts = Post::all()
  2. @comments = Comment::all()

如果我这样做

  1. @post.each ...
  2. ... end
  3. @comments.each ...
  4. ... end

我会得到第一篇文章,然后是评论.但我想要一个时间表,我怎么能创造这个?

我需要结合两个对象来创建一个有序列表,例如:

在帖子中:

  1. id | name | date
  2. 1 | post1 | 2015-01-01
  3. 2 | post2 | 2013-01-01

评论中:

  1. id | name | date
  2. 1 | comment1 | 2014-01-01
  3. 2 | comment2 | 2016-01-01

如果我这样做
post.each …
comments.each …

结果将是:

  1. -post1
  2. -post2
  3. -comment1
  4. -comment2

但我需要按日期订购才能获得

  1. -post2
  2. -comment1
  3. -post1
  4. -comment2

谢谢,对不起我丑陋的英语.

解决方法

帖子和评论是不同的模型(和不同的表),所以我们不能编写sql获取排序集合,分页等.

通常我在需要混合时间线时使用下一种方法.

我有TimelineItem模型,包含source_id,source_type和timeline_at字段.

  1. class TimelineItem < ApplicationRecord
  2. belongs_to :source,polymorphic: true
  3. end

然后我添加模型逻辑以在需要时创建timeline_item实例:

  1. has_many :timeline_items,as: :source
  2. after_create :add_to_timeline
  3.  
  4. def add_to_timeline
  5. timeline_items.create timeline_at: created_at
  6. end

然后搜索输出就像

  1. TimelineItem.includes(:source).order(:timeline_at).each { |t| pp t.source }

猜你在找的Ruby相关文章