link_to_add_association and link_to_remove_association Nested form Cocoon gem

1.1k Views Asked by At

his is the first time I am using cocoon gem so I am not sure how to use it properly,I am not getting error but the link_to_add_association is not working." link_to_remove_association" gives "undefined method `new_record?' for nil:NilClass" error.When I click on link_to_add_association ,nothing happens. Thanks in advance.

_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
1

There are 1 best solutions below

0
nathanvda On

Your form_with command is wrong, you should hand in an actual model instead of the class.

In general one writes

form_with(model: @education, ...

and @education is set in the controller method. E.g. something like

@education = Education.new 

Use of the instance variable instead of writing Education.new also allows us to use the same form for creating new items, rendering invalid items, and editing items.