问题描述
我创建了一个 Ruby on Rails 应用,用户可以在其中记录他们的锻炼,其他用户可以对这些锻炼发表评论.我正在使用仪表板资源来聚合 current_user 的信息.我正在尝试显示有关 current_user 锻炼的最新评论,但似乎无法弄清楚如何正确执行此操作.我想我需要一个我还不擅长的 named_scope.
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.
我本质上希望应用遍历评论表,但只返回关于锻炼的评论,其中锻炼.user_id == 到 current_user.id.
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
/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
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 don't think I need the @workouts line in their but put it anyway.
推荐答案
假设您已正确设置模型,您可以尝试以下方法:
Assuming that you have the models setup properly, here's something you can try:
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
这篇关于我如何调用一个帖子(在这种情况下是锻炼)的所有评论,其中锻炼.user_id == current_user.id?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!