问题
I am trying to build a nested form with the Cocoon Gem. however i am getting the error as shown below. I found another answered question here that Rails Cocoon Gem: Undefined Method 'new_record?' on link_to_remove_association with Wicked. However the only answer has already been ruled out as you can see from my model code.
Error
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
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
Form View
<%= 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%>
Room Partial
<div class="nested-fields">
<%=f.input :name%>
<%= link_to_remove_association "remove task", f%>
</div>
Controller
class TemplatesController < ApplicationController
def new
@template = Template.new
end
def create
end
end
回答1:
The error here is that the simple_fields_for
is not linked to the form-object. So write
<%= f.simple_fields_for :rooms do |room| %>
回答2:
Cocoon is trying to execute f.object.new_record?
and from the error message you are shown, it is clear that f.object
is nil
.
I see that the problem is in the new
action. You have built a blank Template
object, but there isn't any room
associated with it. You have to do this -
def new
@template = Template.new
@template.rooms.build
end
来源:https://stackoverflow.com/questions/19238720/cocoon-gem-undefined-method-new-record-for-nilnilclass-on-link-to-remove-as