# Easier way to pull associated records of has\_many associated

**URL:** <https://www.ruby-forum.com/t/easier-way-to-pull-associated-records-of-has-many-associated/150067>\
**Category:** Rails\
**Created:** [October 3, 2008, 4:20am UTC](https://www.ruby-forum.com/t/easier-way-to-pull-associated-records-of-has-many-associated/150067 "2008-10-03T04:20:59Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![knodi](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/k/bbce88/32.png) [@knodi](https://www.ruby-forum.com/u/knodi)\
**Post date:** [October 3, 2008, 4:20am UTC](https://www.ruby-forum.com/t/easier-way-to-pull-associated-records-of-has-many-associated/150067/1 "2008-10-03T04:20:59Z")

</div>

Currently my User model has has\_many groups and the Group model has\_many  
folders.

so is there any way to pulling all the folders like this.  
user.groups.folders?

Currently I have to loop like this and dump them in to array.

` def user_folders
    user_folders = []
    user_folders.push(self.folders.collect)
    self.groups.each do |group|
      user_folders.push(group.folders.collect)
    end
    user_folders = user_folders.flatten.uniq
  end
`

I get this error  
“ActiveRecord::HasManyThroughSourceAssociationMacroError: Invalid source  
reflection macro :has\_many :through for has\_many :group\_folders,  
:through =\> :groups. Use :source to specify the source reflection.”

User model

` has_many :permissions
  has_many :folders, :through => :permissions
  has_many :members
  has_many :groups, :through => :members
  has_many :group_folders, :through => :groups, :source => :folders
`

Group model

` has_many :members
  has_many :users, :through => :members
  has_many :permissions
  has_many :folders, :through => :permissions
`

So is there a easy way to pull user.groups.folders without looping  
through each group and saving folder in a array?

---

<div class="post-metadata">

**Author:** ![knodi](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/k/bbce88/32.png) [@knodi](https://www.ruby-forum.com/u/knodi)\
**Post date:** [October 3, 2008, 9:06am UTC](https://www.ruby-forum.com/t/easier-way-to-pull-associated-records-of-has-many-associated/150067/2 "2008-10-03T09:06:13Z")

</div>

If you want all folders belonging to all groups for a user, you can  
do:

user.groups.collect{|g| g.folders}.flatten.uniq

which will return all unique folders in an array.

-Brady  
removed\_email\_address@domain.invalid
