在我的 Rails 3 应用程序中,我在 form_for 中使用 fields_for 创建和编辑问题和答案。但是我在 fields_for 上编辑视图以获取答案时遇到问题。当我在数据库中为 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
最后是用于新建和编辑视图的部分:
<%= 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