Skip to content

has_one association

ConfusedVorlon edited this page Jul 2, 2021 · 3 revisions

For has_one association there is one catch. You (probably) have to define force_non_association_create: true because in other case every time the form is rendered the associated object will be destroyed (which is probably not what you expect).

= link_to_add_association('add something', @form_obj, :comments,
    :force_non_association_create => true)

It's easy to overlook this info in the documentation. See also https://github.com/nathanvda/cocoon/pull/247 for more details.

You can use css to automatically hide/show your 'Add Association' button based on whether there is currently a visible association with something like the following:

//This hides the add_association button if there is a .nested-fields which isn't hidden as a sibling
.nested-fields:not([style*="display: none;"]) ~ .links.max-one-association {
	display: none;
}

where your form is showing the association with something like the following:

  %h5 Bar
  .form-group
    = f.fields_for :bar do |bar_form|
      = render 'bar_fields', f: bar_form
    .links.max-one-association
      = link_to_add_association 'add Bar', f, :bar, force_non_association_create: true

and your association fields are under a .nested-fields class

.nested-fields
  %br
  .form-group
    = f.label :title
    = f.text_field :title, class: "form-control", placeholder: "(optional)"
    = link_to_remove_association "remove Bar", f