我有一个 Rails 控制器设置,当用户创建新记录时,它将再次重定向到新操作并用新数据填充表单,这可以继续循环,创建新记录并重定向到新动作。我遇到的麻烦是将 AJAX 添加到此,以便用户可以留在此循环中而无需重新加载页面。这是我没有 AJAX 的代码:
class ResponsesController
def new
@response = Response.new
@answer_a = Answer.find(rand(1..100))
@answer_b = Answer.find(rand(1..100))
@answer_c = Answer.find(rand(1..100))
end
def create
@response = current_user.responses.build(params[:response])
if @response.save
respond_to do |format|
format.html { redirect_to new_response_path }
format.js
end
else
render 'new'
end
end
end
新的.html.erb
<div id="response_form">
<%= render 'form' %>
</div>
_form.html.erb
<%= form_for @response do |f| %>
<%= f.radio_button :user_answer, @answer_a.id %>
<%= @answer_a.description %>
<%= f.radio_button :user_answer, @answer_b.id %>
<%= @answer_b.description %>
<%= f.radio_button :user_answer, @answer_c.id %>
<%= @answer_c.description %>
<%= f.submit "Answer" %>
<% end %>
下面是我尝试添加 AJAX。但是,它将进入表演动作并进行更新。如何修复我的代码,使其不断重定向到新操作,并且用户可以继续在无限循环上创建新记录?
def create
@answer_a = Answer.find(rand(1..100))
@answer_b = Answer.find(rand(1..100))
@answer_c = Answer.find(rand(1..100))
@response = current_user.responses.build(params[:response])
if @response.save
respond_to do |format|
format.html { redirect_to new_response_path }
format.js
end
else
render 'new'
end
end
_form.html.erb
<%= form_for @response, :remote => true do |f| %>
<%= f.radio_button :user_answer, @answer_a.id %>
<%= @answer_a.description %>
<%= f.radio_button :user_answer, @answer_b.id %>
<%= @answer_b.description %>
<%= f.radio_button :user_answer, @answer_c.id %>
<%= @answer_c.description %>
<%= f.submit "Answer" %>
<% end %>
创建.js.erb
$('#response_form').html('<%= j render("form") %>');