Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create array from ActiveRecords Association CollectionProxy

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 ?

like image 774
raphael_turtle Avatar asked Dec 03 '25 01:12

raphael_turtle


2 Answers

I think that

group.topics.includes(:posts).order("posts.published_on").map(&:posts).flatten

would be enough.

like image 70
xlembouras Avatar answered Dec 05 '25 13:12

xlembouras


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)

like image 20
ogabriel Avatar answered Dec 05 '25 13:12

ogabriel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!