0

I'm trying to build a nested form, but the nested form of question_fields isn't rendering in the browser. That form has a nested form called answers, also not rendering

Here's the nested form, _createpoll.html.haml

= form_for Poll.new, :class=>'create-poll-form', :remote => true do |f|
  = f.text_field :title, :autofocus => true, :placeholder => "Poll Title"
  = f.text_field :description, :placeholder => 'Description'

  / Required accepts_nested_attributes_for :questions in the polls model.  
  = f.fields_for :questions do |builder| 
    = render "questions/question_fields", :f => builder

  = f.submit "Create Poll", :class => 'btn btn-danger'

Here's the _questions_fields.html.haml:

%p
  = f.label :content, "Question"
  = f.text_area :content
  = f.check_box :_destroy
  = f.label :_destroy, "Remove Question"
%p
  = f.fields_for :answers do |builder|
    = render "answers/answer_fields", :f => builder

Here's the related Polls Controller, new and create actions

  def create
    @poll = Poll.create(params[:poll])
  end

  def new
    @poll = Poll.new  
    1.times do
      question = @poll.questions.build
      2.times {question.answers.build}
    end
  end

Any ideas on why this might not be rendering? Thanks in advance for the tips!!

Update, a new question

After creating the poll with its associated questions and answers, after querying the database, I see that that the foreign keys aren't persisted and the association is lost. Do I have to use hidden fields here somehow?

1 Answer 1

1

Silly oversight. Poll.new has to be @poll... whoops.

Updating Answer.

This form was was rendered by a button on the user's dashboard, "Create Poll," routing through the controller's new action.

As controller's new action instantiates the new poll, I was being redundant when instantiating another poll in the form for. By switching this to the newly created instance variable @poll, the form rendered. Also, :content threw a no method error, but that's because it wasn't in the attr_accessible of the questions or answers models.

Sign up to request clarification or add additional context in comments.

2 Comments

@Keith - Sounds like you may have figured out the problem yourself? If so, good job :) However, could you elaborate a little? Just so people do not mistake it for a comment or non-answer.
@Leigh Just updated it. Let me know if you have more questions, sorry about the lack of clarity!

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.