Cocoon Gem:未定义的方法`new_record?’ for nil:link_to_remove_association上的NilClass
我正在尝试使用Cocoon Gem构建嵌套表单。 但是我得到的错误如下所示。 我发现Rails Cocoon Gem:Undefined Method’new_record? 在与Wicked的link_to_remove_association上 。 但是,从我的模型代码中可以看出,唯一的答案已被排除。
错误
ActionView::Template::Error (undefined method `new_record?' for nil:NilClass): 1: 2: 3: 4: 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 true end class Room true end class Item < ActiveRecord::Base belongs_to :room end
表单视图
room %>
房间偏好
调节器
class TemplatesController < ApplicationController def new @template = Template.new end def create end end
这里的错误是simple_fields_for
没有链接到表单对象。 所以写
<%= f.simple_fields_for :rooms do |room| %>
Cocoon试图执行f.object.new_record?
并且从显示的错误消息中可以清楚地看出f.object
是nil
。
我看到问题在于new
行动。 您已经构建了一个空白的Template
对象,但没有任何room
与之关联。 你必须这样做 –
def new @template = Template.new @template.rooms.build end