正如你可能要根据组织的用户已经谈到了锻炼的评论意见(相对于没有任何上下文的长长的无差异评论串),首先我建议使用:has_many => through来汇总用户评论过的训练,大致类似(未经测试,显然):
has_many :commented_workouts, :through => :comments, :class_name => 'Workout', :source => :workout, :uniq => true, :order => "created_at desc"
然后,你可以显示在您的ERB类似的意见:
<% current_user.commented_workouts.each do |workout| %>
<%= workout.name %>:
<% workout.comments.each do |comment| %>
<%= comment.text %>
<% end %>
<% end %>
编辑:你也可以这样做:
<% current_user.commented_workouts.each do |workout| %>
<% workout.comments.sort{|x,y| x.created_at <=> y.created_at }.each do |comment| %>
<%= comment.user.name %> just commented on <%= workout.title %>:
<div><%= comment.text %></div>
<% end %>
<% end %>
编辑:或者像这样(注意限制加入到阵列):
class User
def watched_comments
commented_workouts.map(&:comments).flatten.sort{|x,y| x.created_at <=> y.created_at }
end
end
# and in the erb:
<% current_user.watched_comments[0,10].each do |comment| %>
<%= comment.user.name %> just commented on <%= comment.workout.title %>:
<div><%= comment.text %></div>
<% end %>
有一些令人讨厌的n + 1查询福去h这可能不是真正的高性能。或者,你可以尝试让所有的事情都做得更好。喜欢的东西(SQL忍者无疑会做的更好):
编辑:您也可以直接在SQL
has_many :watched_comments, :class_name => 'Comment', :finder_sql => 'select * from comments, workouts where comments.workout_id = workout.id and workouts.id in (select workouts.id from workouts, comments where workouts.id = comments.id and comments.user_id = #{id}) order by comments.created_at desc limit 10'
不就是导致重复添加一个“限制”选项? (让我这样说吧...如果锻炼A有2条评论由用户1,则锻炼A的评论将循环两遍!) – 2010-12-21 23:18:09
我在额外的作业下写道。你是对的。 – 2010-12-21 23:21:01
我更新了代码以防止重复。 – 2010-12-21 23:25:07