views:

29

answers:

1

I have a Project having many Tasks, and each Tasks belongs to a Person.

In my Project edit form, I permit to edit existing tasks and add new ones with the Nested Object Form facility (http://ryandaigle.com/articles/2009/2/1/what-s-new-in-edge-rails-nested-attributes):

<% project_form.fields_for :tasks do |task_form| %>

I want to eager load the associated Task Person objects when fields_for requests the tasks from the database, but I could not find a solution. Is it possible? In the Project model I could define my has_many :tasks with the :include option, but I would rather avoid this as I don't need to eager load Person objects when dealing with a project tasks in general.

For now I've created a second has_many association :tasks_including_person with the corresponding accepts_nested_attributes_for and use it in my fields_for. It works but I would prefer not have to create a specific association like this.

+1  A: 

You can pass a second parameter to fields_for which is the object or collection to render. For example:

project_form.fields_for :tasks, project_form.object.tasks.all(:include => :person) do |task_form|
Jason Weathered
Thanks Jason! and sorry for the long delay of my answer. That what I needed. "tasks(:include => :person)" does not eager load, I just had to change it to "tasks.find(:all, :include => :person)".
Florent2
Oops, that was an oversight on my part. I have updated my example to call `object.tasks.all(:include => :person)`.
Jason Weathered