加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 20:51:49 所属栏目:百科 来源:网络整理
导读:我想显示一个时间链接混合评论和发布所以我有这个对象 @posts = Post::all()@comments = Comment::all() 如果我这样做 @post.each ...... end@comments.each ...... end 我会得到第一篇文章,然后是评论.但我想要一个时间表,我怎么能创造这个? 我需要结合两
我想显示一个时间链接混合评论和发布所以我有这个对象
@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 }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读