I have a simple application that keeps track of projects and tasks:
class Project < ActiveRecord::Base
has_many :Tasks
end
class Task < ActiveRecord::Base
belongs_to :Project
end
In a list view of tasks, I want to show the project name (and link it
to the action allowing the user to edit a project). Currently, that
logic is in the view (which may be my first mistake):
from app/view/task/list.rhtml:
<td><%= link_to Project.find(task.project_id).name, :controller =>
'Project', :action => 'edit', :id => task.project_id %></td>
But this causes the application to make two calls to the database to
get this information: one when the controller pulls its list of tasks:
from app/controller/task_controller.rb:
def list
@task_pages, @tasks = paginate :tasks, :per_page => 10
end
and once when the Project.find() call is executed while parsing the
view. It would be far more efficient, from a database perspective, if
I only had to call on the database once to get the list of tasks.
Probably I could rewrite TaskController.list() to use Task.find() with
the best way to handle this situation? If so, then how do I paginate
the results?
Or is it better to just suck it up, and let Rails make an extra call
to the database for every record returned? It's not so bad when there
are fewer than 10 simultaneous users, and pagination keeps it to 10
tasks per page -- but that's still 11 database transactions per page
when it could just be 1.
Thoughts?