Rails 4 Nested Form.

I am creating a dynamic form for a client. The form has many forms of questions that have many forms of answers. At the moment, I can create everything well in Active Admin and show it through the show action in the application interface. Here is the problem I have. I want to display the title of the form (which works), as well as the questions of the form (which works) along with the input fields for sending new form answers "on the fly" (this is the part that does not work). It seems to me that I have exhausted everything when it comes to nested forms. I will post my code below.

The form

<%= form_for @form do |f| %>
  <div class="field">
    <h1><%= @form.name %></h1>
  </div>
  <%= f.fields_for :form_questions do |ff| %>
    <div class="field">
      <%= ff.label :title  %>
      <%= ff.text_field :form_answers %>
    </div>
  <% end %>
  <div class="form-actions">
    <%= f.button :submit %>
  </div>
<% end %>

Here are the models

class Form < ActiveRecord::Base
  has_many :form_questions, dependent: :destroy
  accepts_nested_attributes_for :form_questions, allow_destroy: true
end

class FormQuestion < ActiveRecord::Base
  belongs_to :form
  has_many :field_types
  has_many :form_answers, dependent: :destroy
  accepts_nested_attributes_for :field_types
  accepts_nested_attributes_for :form_answers
end

class FormAnswer < ActiveRecord::Base
  belongs_to :form_question
end

And my form controller

class FormsController < ApplicationController

  def new
    @form = Form.new
    # form_questions = @form.form_questions.build
    # form_answers = form_questions.form_answers.build
  end

  def create
    @form = Form.new(form_params)
  end

  def index
    @forms = Form.includes(:form_questions).all
  end

  def show
    @form = Form.find(params[:id])
  end

  def edit
    @form = Form.find(params[:id])
  end

  def form_params
    params.require(:form).permit(:id, :name, form_questions_attributes: [:title, form_answers_attributes: [:answer]])
  end


end
+4
source share
1 answer

-, uncomment new. , .

def new
 @form = Form.new
 @form_questions = @form.form_questions.build
 @form_answers = @form_questions.form_answers.build
end

create saving data

def create
 @form = Form.new(form_params)
 if @form.save
   .....
 else
  .....
 end
end

-, form :

<%= form_for @form do |f| %>
  <div class="field">
    <h1><%= @form.name %></h1>
  </div>
  <%= f.fields_for @form_questions do |ff| %>
    <div class="field">
      <%= ff.label :title %>
      <%= ff.text_field :title %>
    </div>  
    <%= ff.fields_for @form_answers do |fa| %> #Here comes the important step
      <div class="field" %>
        <%= fa.label :answer %>
        <%= fa.text_field :answer %>
      </div>
    <% end %> 
  <% end %>
  <div class="form-actions">
    <%= f.button :submit %>
  </div>
<% end %>
+7

All Articles