如何调用所有评论的post(在这种情况下为锻炼),其中exercise.user_id == current_user.id?

我创建了一个Ruby on Rails应用程序,用户可以在其中记录他们的锻炼,其他用户可以对这些锻炼进行评论。 我正在使用仪表板资源来聚合current_user的信息。 我试图在current_user的训练中显示最近的评论,但似乎无法弄清楚如何正确地做到这一点。 我想我需要一个我还不够的named_scope。

我基本上希望应用程序循环遍历评论表,但只返回对锻炼的评论,其中workout.user_id == to current_user.id。

/views/dashboard/index.html.erb

 


dashboard_controller.rb

 def index @comments = Comment.all(:order => "created_at DESC", :limit => 10) @workouts = Workout.all(:order => "created_at DESC", :limit => 10) end 

*我认为我不需要@workouts系列,但无论如何都要。

假设您已正确设置模型,您可以尝试以下方法:

 class Comment < ActiveRecord::Base named_scope :for_user, lambda { |user| { :joins => :workout, :conditions => ["workouts.user_id = ?", user.id] } } named_scope :order, lambda { |order| { :order => order } } named_scope :limit, lambda { |limit| { :limit => limit } } end class DashboardsController < ApplicationController def index @comments = Comment.for_user(current_user).order("created_at DESC").limit(10) end end 

正确的方法是在你的模型之间建立关系,即评论和锻炼。 每个锻炼都可以有很多评论,每个评论都属于锻炼。 所以:

 class Comment < ActiveRecord::Base belongs_to :workout # rest of the model definitions end 

 class Workout < ActiveRecord::Base has_many :comments # rest of the model definitions end 

一旦你这样设置,你可以打电话:

 <% @workout.comments do |comment| %>  <% end %> 

你可以按照这里的例子。