<%= form_with(model: questionnaire) do |form| %> <div class="field"> <%= form.label :name %> <%= form.text_field :name %> </div> <div data-controller="nested-form"> <template data-nested-form-target='template'> <%= form.fields_for :questions, Question.new, child_index: 'TEMPLATE_RECORD' do |question| %> <%= render 'question_fields', form: question %> <% end %> </template> <%= form.fields_for :questions do |question| %> <%= render 'question_fields', form: question %> <% end %> <div data-nested-form-target="add_item"> <%= link_to "Add Question", "#", data: { action: "nested-form#add_association" } %> </div> </div> <div class="actions"> <%= form.submit %> </div> <% end %>
import { Controller } from "@hotwired/stimulus" export default class extends Controller { static targets = ["select", "choice", "long"] connect() { this.selected() } selected() { this.hideFields() switch (this.selectTarget.value) { case 'single_choice': this.choiceTarget.classList.remove('hidden') break; case 'multiple_choice': this.choiceTarget.classList.remove('hidden') break; case 'long_answer': this.longTarget.classList.remove('hidden') break; } } hideFields() { this.choiceTarget.classList.add('hidden') this.longTarget.classList.add('hidden') } }
import { Controller } from "@hotwired/stimulus" export default class extends Controller { static targets = ["add_item", "template"] add_association(event) { event.preventDefault() var content = this.templateTarget.innerHTML.replace(/TEMPLATE_RECORD/g, new Date().valueOf()) this.add_itemTarget.insertAdjacentHTML('beforebegin', content) } remove_association(event) { event.preventDefault() let item = event.target.closest(".nested-fields") item.querySelector("input[name*='_destroy']").value = 1 item.style.display = 'none' } }