0

I am having trouble getting a nested form to work in rails 4.2.0 and ruby 2.2.0. I went back and tried to follow the Railscast from 2010, but even following that example my subfields aren't showing up. What am I doing wrong? Is there a new best practice for nested forms now?

views/surveys/_form.html.erb:

<%= form_for(@survey) do |f| %>
    ...
    <% f.fields_for :questions do |builder| %>
        <div class="field">
          <%= builder.label :content, 'Question' %><br>
          <%= builder.text_area :content, rows: 3 %>
        </div>
    <% end %>
    ...
<% end %>

controllers/survey_controller.rb

class SurveysController < ApplicationController
  before_action :set_survey, only: [:show, :edit, :update, :destroy]
  ...
  # GET /surveys/new
  def new
    @survey = Survey.new
    3.times { @survey.questions.build }
  end
  ...
  private
    ...
    # Never trust parameters from the scary internet, only allow the white list through.
    def survey_params
      params.require(:survey).permit(:name, questions_attributes:[:content])
    end
end

models/questions.rb

# == Schema Information
#
# Table name: questions
#
#  id         :integer          not null, primary key
#  survey_id  :integer
#  content    :text
#  created_at :datetime         not null
#  updated_at :datetime         not null
#

class Question < ActiveRecord::Base
  belongs_to :survey
end

models/surveys.rb

# == Schema Information
#
# Table name: surveys
#
#  id         :integer          not null, primary key
#  name       :string
#  created_at :datetime         not null
#  updated_at :datetime         not null
#

class Survey < ActiveRecord::Base
  has_many :questions, dependent: :destroy
  accepts_nested_attributes_for :questions
end

I'm guessing that this is something simple, but I've spent too much time now trying to figure it out. Does anyone know why my fields aren't showing up?


Solution:

I forgot to render the subfields (<% instead of <%=). The correct text in _form.rb should be:

    <%= f.fields_for :questions do |builder| %>
        <div class="field">
          <%= builder.label :content, 'Question' %><br>
          <%= builder.text_area :content, rows: 3 %>
        </div>
    <% end %>
Lee
  • 686
  • 1
  • 10
  • 23

1 Answers1

1

You need to have <%= on your fields_for

<%= f.fields_for :questions do |builder| %>
    <div class="field">
      <%= builder.label :content, 'Question' %><br>
      <%= builder.text_area :content, rows: 3 %>
    </div>
<% end %>
j-dexx
  • 10,286
  • 3
  • 23
  • 36
  • Thanks, that solved it! I knew it had to be a simple thing I was missing. I'll accept this answer when the site lets me. – Lee Mar 12 '15 at 14:41