我正在使用gem 'nested_form_fields'
,但是当我点击remove
时,它会在浏览器控制台中显示错误
未捕获的TypeError:无法读取未定义的属性'replace' 它也不能被接受来添加或删除嵌套属性。
型号: -
class User < ApplicationRecord
has_many :photos
accepts_nested_attributes_for :photos, allow_destroy: true
end
控制器: -
def new
@user = User.new
@user.photos.build if @user.photos.none?
end
查看: - new.html.erb
<%= form_for @user do |f| %>
<%= render 'shared/errors', object: @user %>
<div class="form-group">
<%= f.label :name %>
<%= f.text_field :name, class: 'form-control' %>
</div>
<div class="form-group">
<%= f.label :email %>
<%= f.email_field :email, class: 'form-control'%>
</div>
<%=f.nested_fields_for :photos do |photo|%>
<%=photo.remove_nested_fields_link 'Remove'%>
<%=photo.file_field :attachment%>
<%=photo.add_nested_fields_link :photos, 'Next Photo'%>
<%end%>
<%= f.submit 'Submit', class: 'btn btn-primary' %>
<% end %>
application.js.erb
: -
//= require jquery
//= require jquery_ujs
//= require nested_form_fields
//= require jquery-ui
//= require turbolinks
//= require_tree .
答案 0 :(得分:0)
我想可能是因为这些代码行
<%=photo.add_nested_fields_link :photos, 'Next Photo'%>
需要在nested_fields_for调用中调用remove_nested_fields_link,并通过父构建器在其外部调用add_nested_fields_link。
所以它应该是
<%= f.add_nested_fields_link :photos, 'Next Photo'%>
所以代码看起来像
<%= form_for @user do |f| %>
<%= render 'shared/errors', object: @user %>
<div class="form-group">
<%= f.label :name %>
<%= f.text_field :name, class: 'form-control' %>
</div>
<div class="form-group">
<%= f.label :email %>
<%= f.email_field :email, class: 'form-control'%>
</div>
<%=f.nested_fields_for :photos do |photo|%>
<%=photo.remove_nested_fields_link 'Remove'%>
<%=photo.file_field :attachment%>
<%end%>
<%=f.add_nested_fields_link :photos, 'Next Photo'%>
<%= f.submit 'Submit', class: 'btn btn-primary' %>
<% end %>