问题
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.
回答1:
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
回答2:
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:
class Comment < ActiveRecord::Base
belongs_to :workout
# rest of the model definitions
end
and
class Workout < ActiveRecord::Base
has_many :comments
# rest of the model definitions
end
Once you set it up like this, then you can call:
<% @workout.comments do |comment| %>
<!-- print comment here -->
<% end %>
You can follow the example here.
来源:https://stackoverflow.com/questions/4311074/how-do-i-call-all-comments-for-a-post-workout-in-this-case-where-workout-user