0

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.

1
  • By the way i will encourage you to use 2 space as indentation for ruby code. If you looking for ruby style guide I will suggest you to look at ruby-style-guide by bbatsov. Commented Jun 3, 2016 at 22:19

1 Answer 1

1

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 %>
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks guys, overlooked this! I moved on to rendering the questions in the show page and now that does not work: <ol> <% for question in @surveycreate.questions %> <li><%=h question.content %></li> <% end %> </ol> This won't render.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.