fields_for表单构建器对象为nil

时间:2010-03-09 14:21:46

标签: ruby-on-rails ruby formbuilder

访问嵌套的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 个答案:

答案 0 :(得分:65)

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

class Project < ActiveRecord::Base
  has_many :tasks
  accepts_nested_attributes_for :tasks ## this is required
end

答案 1 :(得分:13)

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

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

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