2013-10-08 62 views
0

我正在嘗試使用Cocoon Gem創建一個嵌套窗體。但是我得到如下所示的錯誤。我在這裏發現了另一個回答的問題,即Rails Cocoon Gem: Undefined Method 'new_record?' on link_to_remove_association with Wicked。然而,唯一的答案已經被排除,正如你可以從我的模型代碼中看到的。繭寶石:未定義的方法`new_record?' for nil:NilClass on link_to_remove_association

錯誤

ActionView::Template::Error (undefined method `new_record?' for nil:NilClass): 
     1: <div class="nested-fields"> 
     2:  <%=f.input :name%> 
     3:  <%= link_to_remove_association "remove task", f%> 
     4: </div> 
     app/views/templates/_room_fields.html.erb:3:in `_app_views_templates__room_fields_html_erb__1867913568926009508_70125979350780' 
     app/views/templates/_form.html.erb:5:in `block (2 levels) in _app_views_templates__form_html_erb__4123974558704004784_70125994949300' 
     app/views/templates/_form.html.erb:4:in `block in _app_views_templates__form_html_erb__4123974558704004784_70125994949300' 
     app/views/templates/_form.html.erb:1:in `_app_views_templates__form_html_erb__4123974558704004784_70125994949300' 
     app/views/templates/new.html.erb:1:in `_app_views_templates_new_html_erb___3689493092838604682_70125964273280'Models 

模式

class Template < ActiveRecord::Base 
     has_many :rooms 
     accepts_nested_attributes_for :rooms, :allow_destroy => true 
    end 
class Room < ActiveRecord::Base 
     belongs_to :template 
     has_many :items 
     accepts_nested_attributes_for :items, :allow_destroy => true 
    end 
class Item < ActiveRecord::Base 
     belongs_to :room 
    end 

表單視圖

<%= simple_form_for @template do |f| %> 
    <%= f.input :name%> 
    <div id="rooms"> 
     <%= simple_fields_for :rooms do |room| %> 
      <%= render 'room_fields',:f => room %> 
     <%end%> 
     <div class="links"> 
      <%= link_to_add_association 'add room', f, :rooms%> 
     </div> 
    </div> 
<%end%> 

室部分

<div class="nested-fields"> 
     <%=f.input :name%> 
     <%= link_to_remove_association "remove task", f%> 
</div> 

控制器

class TemplatesController < ApplicationController 
    def new 
    @template = Template.new 
    end 

    def create 
    end 
end 
+0

你嘗試用'@ template'替換'f'嗎?我不認爲刪除表格會有任何意義。 – phoet

+0

我試過了,但是從我讀的代碼中不應該引用@template。它的房間。 – gsueagle2008

+0

嗯,這是真的。我的意思是你通過表單構建器而不是對象。所以請嘗試使用'f.object'來訪問底層模型實例。 – phoet

回答

0

繭正試圖執行f.object.new_record?從你所顯示的錯誤信息,很顯然,f.objectnil

我看到問題出在new操作中。你已經建立了一個空白的Template對象,但是沒有任何與之關聯的room。你必須這樣做 -

def new 
    @template = Template.new 
    @template.rooms.build 
end 
1

這裏的錯誤是simple_fields_for沒有鏈接到窗體對象。所以寫

<%= f.simple_fields_for :rooms do |room| %> 
相關問題