Co2
Co2

Reputation: 353

Ruby on Rails Nested Attribute Fields not Showing

I'm following Ryan Bates old tutorial on a survey builder using nested attributes. I have followed it right but for some reason the nested fields don't show in the new action.

Controller: surveycreate.rb

...
    def new
        @surveycreate = Surveycreate.new
        3.times { @surveycreate.questions.build } 
      end
...

Models: surveycreate.rb

class Surveycreate < ActiveRecord::Base
    has_many :questions, :dependent => :destroy
    accepts_nested_attributes_for :questions
end

question.rb

class Question < ActiveRecord::Base
    belongs_to :surveycreate
end

View: surveycreates/_form.html.erb

<%= form_for(@surveycreate) do |f| %>
  <% if @surveycreate.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@surveycreate.errors.count, "error") %> prohibited this surveycreate from being saved:</h2>

      <ul>
      <% @surveycreate.errors.full_messages.each do |message| %>
        <li><%= message %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <%= f.label :name %><br>
  <%= f.text_field :name %>

  <% f.fields_for :questions do |builder| %>
  <p>
    <%= builder.label :content, "Question" %><br />
    <%= builder.text_area :content, :rows => 3 %>
  </p>
  <% end %>


  <div class="actions">
    <%= f.submit :Create %>
  </div>
<% end %>

Schema

create_table "questions", force: :cascade do |t|
    t.integer  "surveycreate_id"
    t.text     "content"
    t.datetime "created_at",      null: false
    t.datetime "updated_at",      null: false
  end

  create_table "surveycreates", force: :cascade do |t|
    t.string   "name"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

end

I'm using rails 4.2.1 and Ruby 2.0. I know the episode is old enough so maybe something has changed here or i'm doing something wrong. Any guidance? Thanks.

Upvotes: 0

Views: 139

Answers (1)

Dmitry Shvetsov
Dmitry Shvetsov

Reputation: 813

You forgot = on the line with f.fields_for. Rails will concat all that will be produced in the fields_for block and you should output it.

  <%= f.fields_for :questions do |builder| %>
    <p>
      <%= builder.label :content, "Question" %><br />
      <%= builder.text_area :content, :rows => 3 %>
    </p>
  <% end %>

Upvotes: 1

Related Questions