Creating a News Feed in Rails 3

I want to create an activity feed from a recent article and comments in my rails app. These are two different types of activerecord (their table structures are different).

Ideally, I could create a mixed array of articles and comments and then show them in reverse chronological order.

So, I can understand how to get an array of articles and comments, and then combine them together and sort by create_at, but I'm sure this will not work as soon as I start using pagination.

Is there a way to create a region as a thing that will create a mixed array?

One of the other problems for me is that it can be all articles, and it can be all comments or some combination between them. Therefore, I can’t just say that I will take the last 15 articles and the last 15 comments.

Any ideas on how to solve this?

+5
source share
2 answers

When I did this earlier , I dealt with it by having a denormalized model UserActivityor similar with a polymorphic association belongs_towith ActivitySource- which can be any types of content that you want to display (messages, comments, voices, preferences, whatever ...).

, , , Observer, UserActivity .

, , UserActivity created_at , activity_source . smarts , -, .

. - ...

user_activity.rb:

class UserActivity < ActiveRecord::Base
  belongs_to :activity_source, :polymorphic => true

  # awesomeness continues here...
end

comment.rb(post/whatever)

class Comment < ActiveRecord::Base
  # comment awesomeness here...
end

activity_source_observer.rb

class ActivitySourceObserver < ActiveRecord::Observer

  observe :comment, :post

  def after_create(activity_source)
    UserActivity.create!(
      :user => activity_source.user, 
      :activity_source_id => activity_source.id, 
      :activity_source_type => activity_source.class.to_s, 
      :created_at => activity_source.created_at, 
      :updated_at => activity_source.updated_at)
  end

  def before_destroy(activity_source)
    UserActivity.destroy_all(:activity_source_id => activity_source.id)
  end

end
+7

railscast.

15 , app/views/articles/index - :

 - @articles.each do |article|
   %tr
     %td= article.body
   %tr
     %td= nested_comments article.comment.descendants.arrange(:order => :created_at, :limit => 15)

:

 #app/models/article.rb
 has_one :comment # dummy root comment

 #app/models/comment.rb
 belongs_to :article
 has_ancestry

:

 root_comment = @article.build_comment
 root_comment.save
 new_comment = root_comment.children.new
 # add reply to new_comment
 new_reply = new_comment.children.new

.

0

All Articles