Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
935 views
in Technique[技术] by (71.8m points)

ruby - 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()

If I do this

@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:

In post:

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

In comments:

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

if I do this post.each ... comments.each ...

the result will that:

-post1
-post2
-comment1
-comment2

But i need order by date to get

-post2
-comment1
-post1
-comment2

Thanks, and sorry for my ugly english.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

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 }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...