3

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 ?

2 Answers 2

6

I think that

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

would be enough.

Sign up to request clarification or add additional context in comments.

1 Comment

Agree with this answer. I'd use .pluck(:posts) instead of .map
2

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.