You can make a method in your model that concatenates the two associations and then sorts them. For example:
def feedback
results = (comments + reviews).sort_by{ |e| e.created_at }
end
If you have a lot of records and want to speed up the process a little bit, you can easily limit the number of results that are returned. Note that you need to order each association independently first, then merge, then sort again.
def feedback max
# We need to get `max` entries from each to ensure that we will have
# enough entries in the final result.
results = comments.order(:created_at).limit(max) + reviews.order(:created_at).limit(max)
# Then, we only return the first `max` entries of the result, since there
# will be `2*max` entries in `results`.
results.sort_by{ |e| e.created_at }.first(max)
end
This leads into the second part of your question.
If you just want the most recent feedback available in the view, then you don't actually need to change your controller action. Instead, you can just access them in the view directly.
Assuming you keep the list of videos in the variable @videos
, this could look like (omitting any ERB/Haml you may be using):
@videos.each do |video|
video.feedback(3).each do |fb|
# do whatever with each feedback item here
end
end
If you need to differentiate between the types of feedback, you can use a case...when
block:
case fb
when Comment
# The feedback is a comment
when Review
# The feedback is a review
end