Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to optimize my activity feed loop (Rails)
    text
    copied!<p>I am implementing an activity feed for my application, much like the facebook news feed. Whenever a user does something (creates a post, comments on a post, creates a photo album, comments on a photo) a row is created in an Activities table, which contains user_id, category, and data. Data is a serialized hash that is different for each type of activity (post contains post title and post id, photo comment contains something else, etc). The view then loops through all of the activities and prints something depending on the category of activity. Pretty simple, and it works. The problem is that it's SUPER slow, so I must be doing something wrong. Here's the code:</p> <pre><code>#activity.rb snippet def post? category == "post" end def post_comment? category == "post_comment" end def album? category == "album" end def photo_comment? category == "photo_comment" end #controller snippet @Activity = Activity.all(:order=&gt; 'created_at DESC', :limit=&gt;"5") #view snippet &lt;% @Activity.each do |a| %&gt; &lt;div class="activity_item"&gt; &lt;div class="avatar" style="background-image: url(&lt;%= small_pic_url(a.user)%&gt;) "&gt;&lt;/div&gt; &lt;div class="text"&gt; &lt;%= a.user.username %&gt; &lt;% if a.post? %&gt; posted &lt;%= link_to a.data["post_title"], post_path(a.data["post_id"]) %&gt; &lt;% elsif a.post_comment? %&gt; commented on &lt;%= link_to a.data["post_title"], post_path(a.data["post_id"]) %&gt; &lt;% elsif a.album? %&gt; created a &lt;%= link_to "Photo Album", album_path(a.data["album_id"])%&gt; &lt;% elsif a.photo_comment? %&gt; commented on &lt;%= link_to "#{a.data["username"]}'s photo", upload_path(a.data["photo_id"])%&gt; &lt;% end %&gt; &lt;/div&gt; &lt;/div&gt; &lt;% end %&gt; </code></pre> <p>I added a user_id index on the activity table, but that didn't seem to do much. Rendering the 5 activity items/avatars takes over 3 seconds, so there must be a better way to handle this.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload