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 に答える