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.
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.