combine 2 objects and sort rails 5

后端 未结 2 1021
南旧
南旧 2020-12-20 05:49

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

2条回答
  •  失恋的感觉
    2020-12-20 06:04

    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 }
    

提交回复
热议问题