# Collections of Custom Entities

**URL:** <https://www.ruby-forum.com/t/collections-of-custom-entities/130987>\
**Category:** Rails\
**Created:** [March 5, 2008, 12:17am UTC](https://www.ruby-forum.com/t/collections-of-custom-entities/130987 "2008-03-05T00:17:58Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![edmz](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/e/898d66/32.png) [@edmz](https://www.ruby-forum.com/u/edmz)\
**Post date:** [March 5, 2008, 12:17am UTC](https://www.ruby-forum.com/t/collections-of-custom-entities/130987/1 "2008-03-05T00:17:58Z")

</div>

I have two entities (Department and Project) that extends  
ActiveRecord::Base. The department is mapped to have many projects. When  
i make a query using the find(:all) (Department.find(:all)), i get a  
collection of the departments with the attributes(id, project\_id) of the  
database. I would like to receive in each department one entity of the  
project class.

I will appreciate any help

* * *

class Department \< ActiveRecord::Base  
has\_many :project  
end

class Project \< ActiveRecord::Base  
end

---

<div class="post-metadata">

**Author:** ![edmz](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/e/898d66/32.png) [@edmz](https://www.ruby-forum.com/u/edmz)\
**Post date:** [March 5, 2008, 6:24pm UTC](https://www.ruby-forum.com/t/collections-of-custom-entities/130987/2 "2008-03-05T18:24:19Z")

</div>

For a ‘has\_many’ association, the Department key should be in the  
Project class (not the other way as it appears from your post). You  
also need to specify the belongs\_to side (Project  
belongs\_to :department) and that is usually the easier one to help  
remember where to place the foreign key: a class belongs\_to another  
class to which it holds a key.

class Department \< ActiveRecord::Base  
has\_many :projects # usually a has many relationship uses the plural  
form  
end

class Project \< ActiveRecord::Base  
belongs\_to :department # the belongs\_to, though, is singular  
end

Department.find(:all, :include=\>:projects)  
This will look up all the departments and eager load (SQL JOIN) the  
projects for each one.

On Mar 4, 6:17 pm, Eduardo D. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid)
