正如你可能要根據組織的用戶已經談到了鍛鍊的評論意見(相對於沒有任何上下文的長長的無差異評論串),首先我建議使用: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