Ruby on rails 如果countive.user\u id==current\u user.id,如何调用帖子(本例中为训练)的所有评论?

Ruby on rails 如果countive.user\u id==current\u user.id,如何调用帖子(本例中为训练)的所有评论?,ruby-on-rails,ruby,named-scope,Ruby On Rails,Ruby,Named Scope,我已经创建了一个RubyonRails应用程序,用户可以记录他们的训练,其他用户可以对这些训练进行评论。我正在使用仪表板资源为当前用户聚合信息。我试图显示最近对当前用户训练的评论,但似乎不知道如何正确操作。我想我需要一个命名的_范围,我还不擅长 我基本上希望该应用程序在注释表中循环,但只返回有关workout.user_id==到当前_user.id的训练的注释 /视图/dashboard/index.html.erb <% @comments.each do |comment| %>

我已经创建了一个RubyonRails应用程序,用户可以记录他们的训练,其他用户可以对这些训练进行评论。我正在使用仪表板资源为当前用户聚合信息。我试图显示最近对当前用户训练的评论,但似乎不知道如何正确操作。我想我需要一个命名的_范围,我还不擅长

我基本上希望该应用程序在注释表中循环,但只返回有关workout.user_id==到当前_user.id的训练的注释

/视图/dashboard/index.html.erb

<% @comments.each do |comment| %> 
  <%= link_to (comment.user.username), comment.user %><br/>
  <%= time_ago_in_words(comment.created_at) %><br/>
  <%= link_to (comment.workout.title), comment.workout %><br/>
<% end %>

*我不认为我需要他们的@workouts行,但不管怎么说。

正确的方法是在模型之间建立关系,即评论和训练。每个训练可以有许多注释,每个注释都属于一个训练。因此:

class Comment < ActiveRecord::Base
      belongs_to :workout

      # rest of the model definitions
end

按此方式设置后,您可以调用:

<% @workout.comments do |comment| %> 
   <!-- print comment here -->
<% end %>

你可以仿效这个例子

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

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

我已经建立了这种关系。当我使用@count.comments do | comment |时,我会得到nil:NilClass的未定义方法注释`那么,我猜您的设置有问题。进一步挖掘。在控制台中工作可能更容易。您可以在freenode上的rubyonrails IRC频道获得即时在线帮助:我怀疑您的@workout实际上是未定义的。你是不是在尝试循环@workouts中的所有内容?如果是这样,局部变量可能是workout,而不是@workout+1,用于将命名的_范围与lambdas一起使用。只是,不需要为order和limit创建一个,使用内置的ActiveRecord方式,如原始帖子所述。这些仅在Rails 3中可用,或者如果您为Rails 2.xYea使用ActiveRecord backport,我正在使用2.3.8进行此项目我在使用上述SQLite3::SQLException:没有这样的列:workout.user\u id:选择comments.*从comments内部加入workouts上的workouts.id=comments.workout\u id其中workout.user\u id=1对不起,应该是workouts.user\u id=?在这种情况下。我已经更新了这个
<% @workout.comments do |comment| %> 
   <!-- print comment here -->
<% end %>
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