Eliminate current_user activity from records returned through a complex association

I created a Ruby on Rails application (Rails 2.3.9) that allows users to track workouts. After creating a workout, other users can comment on this workout. Now I am working on an index view Dashboardto display the latest actions.

In this specific section, I try to display comments from everyone about the workouts that I commented on current_user. I successfully pull these comments, order them and limit the output through the code below.

Now I am trying to exclude comments from the current user. Here is the code:

/views/dashboard/index.html.erb

  <% unless current_user.comment_stream.blank? %>
      <h3>Recent Comments from WODs you commented on</h3>
        <% current_user.comment_stream[0,10].each do |comment| %>
          <p>
             Comment from <%= link_to (comment.user.username), comment.user %> 
             <%= time_ago_in_words(comment.created_at) %> ago on Workout: 
             <%= link_to (comment.workout.title), comment.workout %>
          </p>
        <% end %>
  <% end %>

User.rb

  def workouts_on_which_i_commented
    comments.map{|x|x.workout}.uniq
  end

  def comment_stream
   workouts_on_which_i_commented.map do |w|
     w.comments
   end.flatten.sort{|x,y| y.created_at <=> x.created_at}
  end

Example problem :

, :

A B. C D A. User B , C D ... , .

<% unless comment.user_id == current_user.id %>, , .

0
1

comment_stream ,

def comment_stream
  workouts_on_which_i_commented.map do |w|
    w.comments
  end.flatten.reject{|c| c.user_id == current_user.id}.sort{|x,y| y.created_at <=> x.created_at}
end
0

Source: https://habr.com/ru/post/1782504/


All Articles