I have the following relationship, a discussion which has_many posts which has_many comments
I am trying to implement a personalised user dashboard which orders lastest discussions depending on the user very last change on a particular discussion, so if a user makes a post on a discussion, this discussion should be on the top of the dashboard and if a user makes a comment on any of the posts in a given discussion, this discussion should also now be on the top of his dashboard.
Until now i can only get them to work separately, so i am struggling to combine them.
Only order by last Post:
@discussions = Discussion.joins(:posts).where(posts: {user: current_user}).group('discussions.id').order('MAX(posts.created_at) DESC')
Only order by last Comment:
@discussions = Discussion.joins(:comments).where(comments: {user: current_user}).group('discussions.id').order('MAX(comments.created_at) DESC')
My Attempt to combine them which doesn't work:
@discussions = Discussion.joins(:posts,:comments).where(posts: {user: current_user}).where(comments: {user: current_user}).group('discussions.id').order('MAX(posts.created_at) DESC', 'MAX(comments.created_at) DESC')
This only works depending on what i write on the .order but both never work..
Any help will be much appreciated or any other way of achieving the purpose is also welcome!
Update:
A kind user helped me get a bit further but still not quite the results i am looking for
@discussions = Discussion.joins(:posts,:comments).where(posts: {user: current_user}).where(comments: {user: current_user}).group('discussions.id').order('GREATEST(MAX(posts.created_at), MAX(comments.created_at)) DESC')
The problem here is, that it only works if both a post and a comment exist within a discussion, but i want it to be if either is created the discussion list should be updated with the most recent changed discussion on top.