I have a Group model which has_many Topics. The Topics model has_many Posts.
I want to create an array of all Topics for a Group sorted by the Post attribute :published_on.
On my Group show page I have @group.topics.collect {|x| x.posts } which returns an ActiveRecord::Associations::CollectionProxy array with each element containing an array of post objects.
[
[[topic1 post],[topic1 post],[topic1 post]],
[[topic2 post],[topic2 post],[topic2 post]],
[[topic3 post],[topic3 post],[topic3 post]],
]
How do I create a single array of posts sorted by :published_on ?
I think that
group.topics.includes(:posts).order("posts.published_on").map(&:posts).flatten
would be enough.
You can also resolve this with the correct relations.
On your Group model you could do something like:
# you already have this relation
has_many :topics
# you add this
has_many :posts, through: :topics
That through works using topics like a bridge for posts, and returning all posts that your group have.
And than, your query would look something like
group.posts.order(:published_on)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With