2010-03-09 70 views
33

任何方式來訪問嵌套的form_bulder.object?fields_for表單構建器對象爲零

## 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 

回答

59

您必須在項目模型中有accept_nested_attributes_for才能傳遞對象。

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

你救了我的命..謝謝! – asiniy 2015-10-01 14:46:13

+0

在這上面打了90分鐘。呼。 – DanSingerman 2016-03-04 16:28:42

+0

大約每6個月我都會忘記添加這個,所以很煩人,沒有明顯的錯誤。但我想這可能很難自動檢測。 – 2016-05-03 12:43:24

11

fields_for要求方法tasks_attributes=存在。 accepts_nested_attributes_for :tasks爲你創建這個方法,但是你也可以自己定義:

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

當這個方法不存在,builder.object結束是零。

+0

謝謝你真的很有幫助 – mrageh 2014-08-26 20:08:06