Take the 2-minute tour ×

on my rails 3 app, i'm using fields_for inside a form_for to create and edit questions and answers. But i'm having a problem with Edit view on fields_for for answers. When i have 2 answers registered on the DB for 1 Question, the edit view shows the 2 answers plus a blank field.

Here is the model code, and the views code:

Quesiton Model:

# encoding: utf-8
class Question < ActiveRecord::Base
  attr_accessible :description, :question_id , :research_id , :answer_id  ,:answer_attributes
  has_many :answer, :class_name => "Answer", :dependent => :destroy 
  accepts_nested_attributes_for :answer , :allow_destroy => true
  belongs_to :research

Answer Model:

class Answer < ActiveRecord::Base
  belongs_to :question
  has_many :evaluate_answers
  attr_accessible :question_id, :description , :answer_attributes

And finally the partial used for New and Edit view:

<%= form_for [:admin, @question] ,:html => { :class => "form-horizontal", :multipart =>      true, :onSubmit => " return teste()" } do |f| %>

            <div id="div_respostas" class="respostas" style="margin-top: 25px; margin-left: 65px;">

                <div id="campo_answers">
                    <%= hidden_field_tag :count_resp, 0%>
                    <p>Respostas  <a  href="#"><%=image_tag("admin/icons/btn_adicionar_p.jpg" ,{:onclick =>'add_answer()'}) %></a></p>

                    <%= f.fields_for :answer do |a| %>

                        <div id="answer_<%= @number = @number + 1 %>">
                            <%= a.text_field "description" %>
                            Delete: <%= a.check_box :_destroy %>
                            <a class="button_<%=@number%>" href="#"><%=image_tag("admin/icons/btn_excluir_p.jpg" , {:onclick =>"remove_answer(#{@number})"}) %></a><br /><br />

Everything works fine, just on edit view, there is always one more blank field rendered. Is there a way to remove this blank field?


Question Controller

def edit
    @question = Question.find(params[:id])
    @answers = Answer.where(:question_id => @question.question_id)
    @number = 0
    @questions = Question.all 

Answer Controller

class AnswersController < ApplicationController
  def index
    @answers = Answer.all  


share|improve this question
can you post your controller too please... –  veritas1 Sep 13 '13 at 17:49
Posted at the end –  user2777348 Sep 13 '13 at 18:01
add comment

1 Answer

up vote 4 down vote accepted

It's because you are building a new answer object with this line:


in the edit action of your controller.

So when you visit the edit view, you see the 2 existing answer objects from the database plus the brand new one you've created above.

share|improve this answer
Wow very thanks! I didn't even notice that line. That will do it. Thanks a lot! –  user2777348 Sep 13 '13 at 18:14
No problem. Can you mark this answer as correct if happy with it, many thanks! –  veritas1 Sep 13 '13 at 18:22
add comment

Your Answer


