38

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

2 Answers 2

72

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
3
  • Banged my head on this for about 90 minutes. Whew. Commented Mar 4, 2016 at 16:28
  • 1
    About every 6 month i forget to add this, so annoying that there is no sensible error for this. But i guess it might be hard to detect automatically. Commented May 3, 2016 at 12:43
  • Saved hours of my time - my gratitude is yours. Let this be a lesson to my team while doing some heavy refactoring/cleaning of some old and messy model. (ok...it was me,)
    – Yoopergeek
    Commented Nov 23, 2016 at 1:08
18

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.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.