0

I am trying to do nested forms like mentioned here. http://guides.rubyonrails.org/form_helpers.html#nested-forms

The goal is as follows: I have multiple colli with one checkbox which can be checked. The colli list can be deleted or modified but the checks and their information need to stay.

Model

class Colli < ActiveRecord::Base
  has_one :check, foreign_key: "subcontainerid", primary_key: "colliid"
  accepts_nested_attributes_for :check, allow_destroy: true
end

class Check < ActiveRecord::Base
  belongs_to :colli
end

So every colli has one check. The colliid from the colli table created a link with the check table using the subcontainer id.

Controller

Within the colli controller I whitelist the check_attributes.

def colli_params
  params.require(:colli).permit(:colliid, :collinaam, check_attributes: [:id, :checked])
end

Form

My form looks like this.

<%= form_for(@colli) do |f| %>
  <% if @colli.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@colli.errors.count, "error") %> prohibited this colli from being saved:</h2>

      <ul>
      <% @colli.errors.full_messages.each do |message| %>
        <li><%= message %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <%= f.fields_for :checks do |checks_f| %>
  <p>check start</p>
  <div class="field">
    <%= checks_f.label :checked %><br>
    <%= checks_f.check_box :checked %>
  </div>
  <% end %>

  <div class="field">
    <%= f.label :colliid %><br>
    <%= f.text_field :colliid %>
  </div>

  <div class="field">
    <%= f.label :collinaam %><br>
    <%= f.text_field :collinaam %>
  </div>

  <div class="actions">
    <%= f.submit %>
  </div>

<% end %>

If I do form_for :check I can't see the checkboxes. When I do form_for :checks I see a checkbox but it does not work. When clicking submit I see following error:

undefined method `checked' for nil:NilClass

<p>
  <strong>Checked:</strong>
  <%= @colli.check.checked %>
</p><p>
  <strong>Collinaam:</strong>
  <%= @colli.collinaam %>

Which means it did not get saved. Does anybody know how to fix this?

1 Answer 1

2

Try adding this to your form-

<%= f.fields_for :checks, @colli.check.build do |checks_f| %>
 <p>check start</p>
 <div class="field">
  <%= checks_f.label :checked %><br>
  <%= checks_f.check_box :checked %>
 </div>
<% end %>
Sign up to request clarification or add additional context in comments.

1 Comment

This does not work undefined method build for nil:NilClass but if I do a @colli.build_check in the edit action from the controller it does work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.