I have the following AR associations:
Category :has_many :posts
Category :has_many :authors, :through => :posts
Post :belongs_to :author
Post :has_many :comments
In my view, my goal is to list comments by posts, and posts by author for a particular category. My attempt at a query looks like the following, using includes for eager loading.
category = Category.first
category.authors.includes(:posts => comments)
I’d like my view list out something like:
author1
post1
comment1
post2
comment2
author2
post3
comment3
However, when I try to iterate over the ActiveRecord::Relation object, I’ve noticed that the first level of authors has duplicates and with size equal to the size of posts. Is there a way for me to get unduplicated authors at the first level, and then be able to iterate through associated posts and their comments?
An alternative I thought of was to iterate through the ActiveRecord::Relation object and rewrite it as a hash, but first I wanted to see if there was an AR way of doing this.
One way is to set the :unique property on the relation.
So, category.authors will always return the set of authors.
Check out: rails guides – activerecord