This component is available on GitHub.

Stimulus Rails Nested Form

A Stimulus controller to create new fields on the fly to populate your Rails relationship with accepts_nested_attributes_for.

Nested attributes allow you to save attributes on associated records through the parent.

Installation

$ yarn add stimulus-rails-nested-form

And use it in your JS file:

// Probably in app/javascript/controllers/index.js

import { Application } from '@hotwired/stimulus'
import NestedForm from 'stimulus-rails-nested-form'

const application = Application.start()
application.register('nested-form', NestedForm)

πŸ‘€ Demo

See demo

Usage

In your models:

class User < ApplicationRecord
  has_many :todos
  accepts_nested_attributes_for :todos, reject_if: :all_blank, allow_destroy: true
end

class Todo < ApplicationRecord
  belongs_to :user
end

In your controller:

class UsersController < ApplicationController
  def update
    if user.update(user_params)
      redirect_to users_path
    else
      render :edit
    end
  end

  private

  def user_params
    params
      .require(:user)
       .permit(
         todos_attributes: [:id, :_destroy, :description]
       )
  end
end

To DRY up the code, we extract the fields in a partial called todo_form to use it in the template with a new Todo and in the default fields_for.

In your view:

<%= form_with model: @user, data: { controller: 'nested-form', nested_form_wrapper_selector_value: '.nested-form-wrapper' } do |f| %>
  <template data-nested-form-target="template">
    <%= f.fields_for :todos, Todo.new, child_index: 'NEW_RECORD' do |todo_fields| %>
      <%= render "todo_form", f: todo_fields %>
    <% end %>
  </template>

  <%= f.fields_for :todos do |todo_fields| %>
    <%= render "todo_form", f: todo_fields %>
  <% end %>

  <!-- Inserted elements will be injected before that target. -->
  <div data-nested-form-target="target"></div>

  <button type="button" data-action="nested-form#add">Add todo</button>

  <%= f.submit 'Save todos' %>
<% end %>

In the _todo_form.html.erb partial:

<div class="nested-form-wrapper" data-new-record="<%= f.object.new_record? %>">
  <%= f.label :description %>
  <%= f.text_field :description %>

  <button type="button" data-action="nested-form#remove">Remove todo</button>

  <%= f.hidden_field :_destroy %>
</div>

As explained in the documentation, we need to specify the child_index and replace its value in JavaScript because the index needs to be unique for each fields.

πŸ›  Configuration

AttributeDefaultDescriptionOptional
data-nested-form-wrapper-selector-value.nested-form-wrapperSelector to find the wrapper.βœ…

The remove feature is completely optional.

πŸŽ› Extending Controller

You can use inheritance to extend the functionality of any Stimulus component:

import NestedForm from 'stimulus-rails-nested-form'

export default class extends NestedForm {
  connect() {
    super.connect()
    console.log('Do what you want here.')
  }
}

This controller will automatically have access to targets defined in the parent class.

If you override the connect, disconnect or any other methods from the parent, you'll want to call super.method() to make sure the parent functionality is executed.

β˜•οΈ Sponsors

Stimulus Component is an MIT licensed open source project and completely free to use. However, the amount of effort needed to maintain and develop new features for the project is not sustainable without proper financial backing. You can support Stimulus Components development on Github Sponsors. πŸ™

πŸ‘· Contributing

Do not hesitate to contribute to the project by adapting or adding features ! Bug reports or pull requests are welcome.

Don’t forget to drop a 🌟 on Github to support the project.

πŸ“ License

This project is released under the MIT license.