Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fields_for form builder object is nil

Any way to access a nested form_bulder.object?

## controller
@project = Project.new
@project.tasks.build

form_for(@project) do |f|
  f.object.nil? ## returns false

  fields_for :tasks do |builder|
    builder.object.nil? ## returns true
  end
end
like image 284
Chap Avatar asked Mar 09 '10 14:03

Chap


2 Answers

You must have accepts_nested_attributes_for in the Project model in order for the object to be passed.

class Project < ActiveRecord::Base
  has_many :tasks
  accepts_nested_attributes_for :tasks ## this is required
end
like image 104
Chap Avatar answered Nov 14 '22 07:11

Chap


fields_for requires that the method tasks_attributes= exists. accepts_nested_attributes_for :tasks creates this method for you, but you can also just define it yourself:

def tasks_attributes=(params)
  # ... manually apply attributes in params to tasks
end

When this method does not exist, the builder.object ends up being nil.

like image 44
Matt Connolly Avatar answered Nov 14 '22 06:11

Matt Connolly