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.
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.
Assuming that you have the models setup properly, here's something you can try: