38

有什么方法可以访问嵌套的 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
4

2 回答 2

71

您必须在 Project 模型中具有 accept_nested_attributes_for 才能传递对象。

class Project < ActiveRecord::Base
  has_many :tasks
  accepts_nested_attributes_for :tasks ## this is required
end
于 2010-03-09T16:45:17.360 回答
17

fields_for要求该方法tasks_attributes=存​​在。accepts_nested_attributes_for :tasks为您创建此方法,但您也可以自己定义它:

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

当此方法不存在时,builder.object最终为零。

于 2014-06-25T10:39:10.273 回答