有什么方法可以访问嵌套的 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
有什么方法可以访问嵌套的 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
您必须在 Project 模型中具有 accept_nested_attributes_for 才能传递对象。
class Project < ActiveRecord::Base
has_many :tasks
accepts_nested_attributes_for :tasks ## this is required
end
fields_for
要求该方法tasks_attributes=
存在。accepts_nested_attributes_for :tasks
为您创建此方法,但您也可以自己定义它:
def tasks_attributes=(params)
# ... manually apply attributes in params to tasks
end
当此方法不存在时,builder.object
最终为零。