The RoR App has posts and categories, the main view is a row set of categories/posts. It shows posts (newer than 3 days) per category. Empty categories are not shown.
I want to sort the index view to show first the categories with more recent posts. So when a new post is created for a category, the category goes up to the first "row" of the app. Inside a category, posts should be also sorted from newer to older.
Therefore I need to implement two levels of sorting, categories with newest post go first and posts are sorted by creation date inside a category. I am really stuck, how would you implement this?
My controller:
def index
@categories = Category.includes(:posts).select{|c| c.posts.where(['created_at > ?', 3.days.ago]).count > 0}
end
My view:
<% @categories.each do |category| %>
# show category name
<% category.posts.where(['created_at > ?', 3.days.ago]).each do |post| %>
# show post title and date
<% end %>
<% end %>
UPDATE: to show what I've tried so far:
I tried to sort the @categories first, based on the posts' creation_date (as explained, Category has_many:posts). In my controller:
@categories = Category.includes(:posts).order('posts.created_at').select{|c| c.posts.where(['created_at > ?', 3.days.ago]).count > 0}
Then in my view, sort the posts as they are loaded:
<% @categories.each do |category| %>
# show category name
<% category.posts.order('created_at').where(['created_at > ?', 3.days.ago]).each do |post| %>
# show post title and date
<% end %>
<% end %>
Regarding the counter_cache sugestion; I understand it'd be only for optimization of database calls, although not strictly necessary.
SOLUTION: it can be done as stated in the previous UPDATE; but with the change of order('posts.created_at') per order('posts.created_at DESC') in the controller; and the change of order('created_at') per order('created_at DESC') in the view.