Reputation: 4087
sorry for my beginner question but i'm trying to learn RoR. In Rails 3.2 i've declared:
class Project < ActiveRecord::Base
attr_accessible :name, :description
has_many :subprojects
end
class SubProject < ActiveRecord::Base
attr_accessible :id_name, :description, :num_alloc, :project_id
belongs_to :projects
end
How can i show, in a view, a table with the attributes id_name, num_alloc (from SubProject) and name (from Project)
How can i make the join? In the controller, if i make:
@results= SubProject.joins('LEFT OUTER JOIN.......)
this, return only the SubProject attribute right?
Thanks
Upvotes: 1
Views: 102
Reputation: 15089
There is a thing called eager loading. When you make a query with a join, and create the objects, these associations are prepopulated. For example:
@results = SubProject.joins(:project)
In your view, or any other place, if you call the project object inside subproject, you will have direct access to its content, without making another query.
@results.each do |r|
puts r.project.name # The project is prepopulated from the db
end
If you don't care about performance, you can just fecth the subprojects and for each one of them query the project inside.
@results = SubProject.all
@results.each do |r|
puts r.project.name # This will make other query
end
Upvotes: 2