0

我有一个用于创建问题和答案的新表格。这是我的表格:

<%= simple_form_for [@question_type, @question], url: path, defaults: { error: false } do |question_form| %>
  <%= render 'shared/error_messages', object: question_form.object %>

  <div class="question_fields well">
    <%= question_form.input :content, input_html: { rows: 4, class: 'span6' } %>
    <%= question_form.input :mark, input_html: { class: 'span1' } %>
    <%= question_form.association :topic %>
  </div>
  <%= question_form.simple_fields_for :answers do |answer_form| %>
    <%= render 'answer', f: answer_form %>
  <% end %>
  <%= question_form.button :submit, class: "new_resource" %>
<% end %>

该问题有 3 个字段:内容、标记、主题。

这是我create有问题的控制器操作:

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

  if @question.save
    flash[:success] = "Successfully created question."
    redirect_to new_question_type_question_path
  else
    render 'new'
  end
end

我的路线:

resources :question_types, only: [:index] do
  resources :questions
end

现在,我想在用户提交创建问题成功后,它会再次显示新表单,但topic选择会显示刚刚保存的问题主题。我怎样才能做到这一点?

4

1 回答 1

1

#1 解决方案 -

如果我正确理解了您的问题,您可以在问题成功保存后将问题的 topic_id 传递给新操作。

redirect_to new_question_type_question_path(:topic_id => @question.topic_id )

然后在问题控制器的新操作中,如果 params[:topic_id] 存在,则添加 topic_id?

像这样的东西,

def new
  ...
  ...
  @topic_id = params[:topic_id] if params[:topic_id].present?
end

然后以新形式,使用此 @topic_id 实例变量显示您的主题。我对 simple_form_for 了解不多,但你可以做类似的事情,

<%= question_form.association :topic, :selected => (@topic_id.present? ? @topic_id : '') %>

或者

#2 解决方案

要显示保存的最后一个问题的主题,您只需要新操作中的最后一个问题对象。您不需要执行 #1 解决方案的上述步骤

def new
  ...
  ...
  @topic_id = current_user.questions.order('created_at ASC').last.topic_id if current_user.questions.present?
end

以新的形式做与#1解决方案相同的事情,

<%= question_form.association :topic, :selected => (@topic_id.present? ? @topic_id : '')
于 2012-11-12T14:33:23.453 回答