通过复杂的关联返回从记录消除CURRENT_USER活动 [英] Eliminating current_user activity from records being returned through a complex association
问题描述
我已经建立了一个Ruby on Rails应用程序(Rails的2.3.9),允许用户跟踪训练。锻炼创建后其他用户可以对锻炼发表评论。我现在工作的控制台
索引视图,显示最近的活动。
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.
在这个特殊的部分,我想显示所有在该锻炼CURRENT_USER
的评论意见。我成功地拉这些意见,命令他们,并限制通过以下code的输出。
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.
我现在想排除从当前用户的意见。这里是code:
I am now trying to exclude comments from current user. Here is the code:
/views/dashboard/index.html.erb
/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
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
问题的示例
下面是一个什么与此code发生了一个例子:
Here is an example of what happens with this code:
用户A创建上有一个锻炼和用户B的意见。然后,用户C和用户D还对用户A的训练发表评论。在用户B的仪表板视图,我希望他看到从活动流中用户C和用户D的评论......但我不想让他看到了自己的意见。
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 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.
我可以简单地使用&LT;%,除非comment.user_id == current_user.id%GT;
但食堂被显示为这些记录的数量捕捞之前排除线。
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.
推荐答案
在comment_stream,您可以添加过滤掉你发布
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
这篇关于通过复杂的关联返回从记录消除CURRENT_USER活动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!