0

我有这样的表格:

新问题

当我提交没有任何内容的表单时,它会显示错误:

错误新问题

单选按钮丢失了!

这是在我的表单视图中:

<%= simple_form_for @question, defaults: { error: false } do |q| %>

  <legend>Question</legend>
  <%= render "shared/error_messages", object: q.object %>

  <%= q.input :content, input_html: { rows: 3, class: 'span6' } %>
  <%= q.input :mark, input_html: { class: 'span1' } %>
  <%= q.association :topic %>
  <%= q.association :question_type %>

  <%= q.simple_fields_for :answers do |a| %>
    <%= a.input :correct, collection: [[true, 'True'], [false, 'False']],
                                                            as: :radio_buttons,
                                                            label: 'Answer',
                                                            value_method: :first,
                                                            label_method: :last,
                                                            item_wrapper_class: 'inline'
                                                            %>
  <% end %>
<% end %>  

我错过了什么或错了什么?render 'new'当@question.save 为假时,我在问题控制器的创建操作中使用了。这是我的问题控制器:

class QuestionsController < ApplicationController
  def new
    @question = Question.new
    @question.answers.build
  end

  def create
    @question = Question.new(content: params[:question][:content])
    @question.mark = params[:question][:mark]
    @question.topic_id = params[:question][:topic_id]
    @question.question_type_id = params[:question][:question_type_id]
    @question.user_id = current_user.id

    if @question.save
      if params[:question][:answers_attributes]['0'][:correct] == 'true'
        answer = @question.answers.build(content: 'True')
        answer.correct = true
      else
        answer = @question.answers.build(content: 'False')
      end
      if @question.save
        flash[:success] = "Successfully created new question."
        redirect_to root_url
      else
        render 'new'
      end
    else
      render 'new'
    end
end
4

2 回答 2

2

我猜你正在控制器中的对象上answer使用build_answer方法(或其他方式)构建一个新的@question,可能在new方法中。

发生的情况是,当create操作失败时,@question没有answers,并且simple_fields_for不会显示任何内容。

如果您需要更多详细信息,请发布您的控制器的代码,我们将尝试找出解决问题的方法。

编辑:您构建问题的方式是错误的,应该是

@question = Question.new(params[:question])

那么您@question将得到答案,并且在您看来一切都会正常进行;)

于 2012-10-28T15:05:25.647 回答
0

在上次渲染“新”上方添加了@question.answers.build,现在可以使用

于 2012-10-30T06:23:56.803 回答