How do I create a facebook style news feed in ruby on rails?

后端 未结 3 1623
我在风中等你
我在风中等你 2020-12-12 13:44

I am trying to fuse to objects into a single stream.

I created a new model and controller called Newsfeed. I have it so that newsfeed has_many :messages and has_many

3条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-12 14:02

    I'm sure this can be streamlined from it's ghetto-polymorphism, but it works for me, and I had an identical struggle with the "how do I combine all these model results?!"

    I use a separate model, like you, and an observer:

    class NewsfeedObserver < ActiveRecord::Observer
    
      observe Message, Image
    
      def after_save(object)
        @item = Newsfeed.create(
                  :item_id => object.id, 
                  :item_type => object.class.to_s
        )
      end
    end
    

    Then in the Newsfeed model you can pull and collate as you like:

    def self.get_items
      item_list = []
      items = find(:all, :order => "created_at DESC", :limit => 30)
      items.collect{ |i| i.item_type.constantize.find(i.item_id) }
    end
    

    Then just pull them and display in your view however you like.

    #Controller
    def index
      @feed = Newsfeed.get_items
    end
    

    Moving forward I will probably start to pack more into the stream-tracking model in order to save hits on the other tables, but hopefully you get the idea.

提交回复
热议问题