Eliminating current_user activity from records being returned through a complex association
I have built a Ruby on Rails application (Rails 2.3.9) that allows users to track workouts. After a workout is created other users can comment on that workout. I am now working on the Dashboard
index view to display recent activity.
In this particular section I am trying to display comments from all on workouts that current_user
has commented on. I am successfully pulling those comments, ordering them, and limiting the output through the below code.
I am now trying to exclude comments from 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 of Problem:
Here is an example of what happens with this code:
User A creates a workout and User B comments on it. Then User C and User D also comment on User A's workout. In User开发者_Python百科 B's dashboard view, I want him to see comments from User C and User D in the activity stream...but I don't want him to see his own comments.
I could simply use a <% unless comment.user_id == current_user.id %>
but that messes up the number of records being displayed as those are fished prior to the exclusion line.
In comment_stream, you can add filter out the comments you posted
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
精彩评论