我有一个用于创建问题和答案的新表单。这是我的表格:
<%= 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
选择将显示刚刚保存的问题主题。我怎么能这样做?
答案 0 :(得分: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 : '') %>
OR
#2解决方案
要显示上次保存问题的主题,您只需要在新操作中使用最后一个问题对象。 您无需执行#1解决方案的上述步骤
def new
...
...
@topic_id = current_user.questions.order('created_at ASC').last.topic_id if current_user.questions.present?
end
以新形式做同样的事情,如#1 Solution,
<%= question_form.association :topic, :selected => (@topic_id.present? ? @topic_id : '')