I need to find all the groups created by the current user and then find all the posts combined present in these groups and then display them in a timeline in a reverse order. Below is the code for only the post of a single group. How could I do this for all the groups and make sure it is database optimised as well.
So then you could do what you were doing before i.e. @posts = (alerts + notes).sort_by(&:created_at).reverse.
With your code you will grab all the groups and then make two requests for each group to get their alerts and notes. By using includes you make one database request instead of many. The sorting and reverse shouldn’t be too expensive.
I don’t know of a way through activerecord to get all the data you want already sorted. There may be a way using Arel for which there is a railscast.
Thanks @DeviousDuck. Even I had thought about having a class called Post which either could be a note or an alert and have polymorphism and use Group has_many posts, something like that, when I got stuck and posted this problem here.
But now I am trying to figure out a way to do current_user.posts which will then straight return me the combination of the alerts and notes.
I thought
User has_many :posts
but then have a polymorphic relation between the post and the alerts/notes because a post could be either an alert or a note.
Or should I instead have a method on the User def post which then returns me self.alerts + self.notes?
But in this case then I would to create a corresponding post for any previous alerts, notes created. I read that thoughtbot article. But not much made sense to me.