Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3: fields_for showing blank filed on Edit view

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:

Question 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
end

Answer Model:

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

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 />
                        </div>
                    <%end%>

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

EDIT:

Question Controller

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

Answer Controller

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

  end

end
like image 716
user2777348 Avatar asked Sep 13 '13 17:09

user2777348


1 Answers

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

@question.answer.build

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.

like image 107
veritas1 Avatar answered Sep 19 '22 12:09

veritas1