Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to apply a scope to an association when using fields_for?

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.

like image 717
Florent2 Avatar asked Jun 16 '10 20:06

Florent2


1 Answers

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|
like image 162
Jason Weathered Avatar answered Sep 18 '22 18:09

Jason Weathered