我正在使用will_paginate分页来调查问题。
每个问题都有答案。
每个页面包含5个问题。在转到下一页时,我丢失了上一页的答案。如何在before_paginate之前保存这些记录。
<%= form_for(@attempt, :url => attempt_scope(@attempt)) do |f| %>
<%= f.fields_for :answers do |builder| %>
<div id="accordion" class="questions">
<% @questions.each_with_index do |question, index| %>
<h3 data-id="<%= question.id %>" >Question </h3>
<div>
<p> <div><%= question.text %> </div>
<%= hidden_field_tag "survey_attempt[answers_attributes][#{index}][question_id]", question.id %>
</p>
<div class="input select rating-c">
<label for="example-c">Rating values displayed on the bars:</label>
<%#=select_tag "survey_attempt[answers_attributes][#{index}][option_id][]", options_from_collection_for_select(@options, "id", "text"),{ class: " #{question.id}list select mybutton",id: "example-c",include_blank: true, name: "optionname"} %>
<%=select_tag "survey_attempt[answers_attributes][#{index}][option_id][]", options_from_collection_for_select(@options, "id", "text"),{id:"example-c"} %>
</div>
</div>
<% end %>
</div>
<%= will_paginate @questions, :class=>"mybutton page pagination", renderer: BootstrapPagination::Rails, params: request.params %>
<% end %>
<%= f.submit "Submit" %>
答案 0 :(得分:2)
为什么不在用户检查或选择选项时使用ajax提交答案。您可以获得有关ajax here
的更多信息修改强>
有两种方法可以执行ajax,要么你可以去远程:你的表单中的true,我在之前发布的链接中解释过,或者你可以通过jquery调用ajax请求。我认为jquery one会更清洁。
假设您有一个问题答案的复选框。你会得到这样的东西:
<input type="checkbox" class="answers"> #but each question will have different answers so you need something to differentiate so you will need some data attribute.
<input type="checkbox" class="answers" data-question="question_id">
现在,您可以通过一个jquery函数来定位每个答案,如下所示:
$(document).on("click",".answers",function(){
var question = $(this).data("question"); #gets the id of question
$.ajax({
url: url_for_your_custom_action, #need to make a method in controller and create answer for that question by the id of question you get from content in params
type: "POST", #a post request because you sending question id.
data: { content: question } #this will send your question id. you can get it by params[:content]
});
});
这样,无论用户选中哪个复选框,都会调用相同的方法,您不必重复代码。