如何调用锻炼.user_id == current_user.id 的帖子(在本例中为锻炼)的所有评论?
我创建了一个 Ruby on Rails 应用程序,用户可以在其中记录他们的锻炼,其他用户可以对这些锻炼发表评论。我正在使用仪表板资源来聚合 current_user 的信息。我正在尝试显示有关 current_user 锻炼的最新评论,但似乎无法弄清楚如何正确执行此操作。我想我需要一个我还不擅长的named_scope。
我本质上希望应用程序循环浏览评论表,但只返回有关“锻炼”的评论,其中“workout.user_id ==”到“current_user.id”。
/views/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 %>
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 行,但无论如何都要放它。
I have created a Ruby on Rails app where users can record their workouts and other users can comment on those workouts. I am using a Dashboard resource to aggregate information for current_user. I am trying to display recent comments on a current_user's workouts but can't seem to figure out how to do this correctly. I think I need a named_scope which I am not great at yet.
I essentially want the app to loop through the comments table but only return comments on Workouts where workout.user_id == to current_user.id.
/views/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 %>
dashboard_controller.rb
def index
@comments = Comment.all(:order => "created_at DESC", :limit => 10)
@workouts = Workout.all(:order => "created_at DESC", :limit => 10)
end
*I don't think I need the @workouts line in their but put it anyway.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
假设您已正确设置模型,您可以尝试以下操作:
Assuming that you have the models setup properly, here's something you can try:
正确的方法是在模型之间建立关系,即评论和锻炼。每个锻炼可以有许多评论,每个评论都属于一个锻炼。所以:
一旦
你像这样设置它,那么你就可以调用:
你可以按照示例
The proper way to do is to put relations between your models, i.e. comment and workout. Each workout can have many comments, and each comment belongs to a workout. So:
and
Once you set it up like this, then you can call:
You can follow the example here.