组合 2 个对象并排序 Rails 5 [英] combine 2 objects and sort rails 5
问题描述
我想显示一个混合评论和帖子的时间链接,所以我有这个对象
I want to show a time link mixing comments and post so I have this objects
@posts = Post::all()
@comments = Comment::all()
如果我这样做
@post.each ...
... end
@comments.each ...
... end
我会收到第一篇帖子,然后是评论.但我想要一个时间表,我该如何创建?
I will get first posts and after this, the comments. But I want a timeline, how i can create this?
我需要结合两个对象来创建一个有序列表,例如:
I need to combine both object to create just one ordered list, example:
在帖子中:
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
如果我这样做后.每个...评论.每个...
if I do this post.each ... comments.each ...
结果是:
-post1
-post2
-comment1
-comment2
但我需要按日期订购
-post2
-comment1
-post1
-comment2
谢谢,对不起,我的英语很丑.
Thanks, and sorry for my ugly english.
推荐答案
帖子和评论是不同的模型(和不同的表),所以我们不能写 SQL 来获取排序集合,带分页等.
Posts and comments are different models (and different tables), so we can't write SQL to get sorted collection, with pagination etc.
当我需要混合时间线时,我通常会使用下一个方法.
Usually I use next approach when I need mixed timeline.
我有带有 source_id
、source_type
和 timeline_at
字段的 TimelineItem
模型.
I have TimelineItem
model with source_id
, source_type
and timeline_at
fields.
class TimelineItem < ApplicationRecord
belongs_to :source, polymorphic: true
end
然后我添加模型逻辑以在需要时创建时间线项目实例:
Then I add in models logic to create timeline_item instance when needed:
has_many :timeline_items, as: :source
after_create :add_to_timeline
def add_to_timeline
timeline_items.create timeline_at: created_at
end
然后搜索输出就这么简单
Then search and output as simple as
TimelineItem.includes(:source).order(:timeline_at).each { |t| pp t.source }
这篇关于组合 2 个对象并排序 Rails 5的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!