I have a new form for create question and answers. This is my form:
<%= 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 %>
The question have 3 fields: content, mark, topic.
This is my create
action in question controller:
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
My routes:
resources :question_types, only: [:index] do
resources :questions
end
Now, i want after user submit to create question successful, it will show new form again, but the topic
select will display the topic of question was just saved. How can i do that?
#1 Solution -
If I understood your question correctly you can pass question's topic_id to new action after question saved successfully.
redirect_to new_question_type_question_path(:topic_id => @question.topic_id )
then in new action of questions controller, add topic_id if params[:topic_id] present?
something like this,
def new
...
...
@topic_id = params[:topic_id] if params[:topic_id].present?
end
then in new form, display your topic using this @topic_id instance variable. I don't know too much about simple_form_for, but you can do something like,
<%= question_form.association :topic, :selected => (@topic_id.present? ? @topic_id : '') %>
OR
#2 Solution
To display the topic of last question saved, you just need last question object in new action. You don't need to do above steps of #1 Solution
def new
...
...
@topic_id = current_user.questions.order('created_at ASC').last.topic_id if current_user.questions.present?
end
In new form do same thing as given in #1 Solution,
<%= question_form.association :topic, :selected => (@topic_id.present? ? @topic_id : '')