问题描述
他是我第一次使用茧状宝石,因此我不确定如何正确使用它,我没有收到错误消息,但是link_to_add_association无法正常工作。“ link_to_remove_association”给出了“未定义的方法'new_record?'”。 for nil:NilClass“错误。当我单击link_to_add_association时,没有任何反应。 预先感谢。
_education_fields.html.erb
<div class="nested-fields">
<div class="field">
<%= f.label :institute_name %>
<%= f.text_field :institute_name %>
</div>
<div class="field">
<%= f.label :qualification %>
<%= f.text_field :qualification %>
</div>
<div class="field">
<%= f.label :specification %>
<%= f.text_field :specification %>
</div>
<div class="field">
<%= f.label :start_date %>
<%= f.date_select :start_date %>
</div>
<div class="field">
<%= f.label :end_date %>
<%= f.date_select :end_date %>
</div>
<div class="field">
<%= f.label :marks %>
<%= f.text_field :marks %>
</div>
<%= link_to_remove_association "remove task",f,class: 'btn btn-primary btn-xs' %>
</div>
_form.html.erb
<%= form_with(model: Education,url: user_educations_path,method: :post,local: true) do |form| %>
<% if @user.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@user.errors.count,"error") %> prohibited this education from being saved:</h2>
<ul>
<% @user.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class='user_educations'>
<%= form.fields_for :educations do |education| %>
<%= render 'education_fields',f: education %>
<% end %>
</div>
<div class="actions">
<%= form.submit %>
</div>
<div class="text-right">
<%= link_to_add_association 'Add more',form,:educations %>
</div>
<% end %>
user.rb
class User < ApplicationRecord
has_many :educations,dependent: :destroy
accepts_nested_attributes_for :educations,reject_if: :all_blank,allow_destroy: true
end
解决方法
您的form_with
命令是错误的,您应该提交实际模型而不是类。
通常一个人写
form_with(model: @education,...
在控制器方法中设置了和@education
。例如。像
@education = Education.new
使用实例变量代替编写Education.new
也使我们可以使用相同的形式来创建新项目,渲染无效项目和编辑项目。