Rails 3:fields_for在编辑视图上显示空白字段

时间:2013-09-13 17:32:54

标签: ruby-on-rails ruby ruby-on-rails-3

在我的Rails 3应用中,我在form_for中使用fields_for来创建和编辑问题和答案。但是我在fields_for上编辑视图时遇到问题需要答案。当我在DB上为1个问题注册了2个答案时,编辑视图显示2个答案加上一个空白字段。

以下是型号代码和视图代码:

问题模型:

# 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

答案型号:

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

最后用于New和Edit视图的部分:

<%= 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%>

一切正常,仅在编辑视图中,总会再渲染一个空白字段。有没有办法删除这个空白字段?

编辑:

问题控制器

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

回答控制器

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

  end

end

1 个答案:

答案 0 :(得分:7)

这是因为您正在使用以下行构建新的答案对象:

@question.answer.build

在您的控制器的edit操作中。

因此,当您访问编辑视图时,您会看到数据库中的2个现有答案对象以及您在上面创建的全新答案对象。