我有一个表单,其中我正在使用ajax验证,因为我已将表单设为:remote =>为true,视图为
<%= nested_form_for @interview_round, :remote => true do |f| %>
<div id="error-div"> </div>
<%= f.text_field :interviewer_name %>
<%= f.text_field :log_skill, :id=>'hint-log' %>
<%= f.text_field :comm_skill, :id=>'hint-comm' %>
<%= f.submit %>
<% end %>
,控制器为
def update
@interview_round = InterviewRound.where(id: params[:id]).first
respond_to do |format|
if @interview_round.update_attributes round_params
format.html{ redirect_to interview_path(@interview_round.interview_id), notice: I18n.t('round_created')}
format.js
else
format.html { render :action => "edit" }
format.js
end
end
end
我在update.js.erb
中显示错误<% if @interview_round.errors.present?%>
$('#error-div').html('<%= j(render 'shared/error_messages', :target => @interview_round) %>');
<% else %>
$('form.edit_interview_round').removeAttr('data-remote')
<% end %>
现在,当我提交表单时,错误将通过ajax远程显示并显示在页面上,但是当我提交表单时没有任何错误,页面不会重定向到所需的页面,但它将数据存储在数据库中并提交表单,虽然我也试图删除表单上的数据远程,当它没有错误,它在HTML中删除但仍然在我提交时页面没有加载
请帮助!!
答案 0 :(得分:2)
当您使用remote:true时,您无法通过&#39;重定向&#39;重定向?因为它是一个&#39;脚本&#39;请求并且不会创建新的页面/标题等。
例如,以下方法可行,语法很难看,但这会重定向:
format.html{ redirect_to interview_path(@interview_round.interview_id), notice: I18n.t('round_created')}
format.js { render js: "window.location.href = '#{interview_path(@interview_round.interview_id)}'" }
但是,您最好在单独的.js视图文件中执行JS代码。如果你在名为update.js的HTML视图所在的同一目录中创建一个视图文件,然后在那里重新导入javascript,你可以删除我给你的行,并在视图中保持视图相关的代码。
为此,您需要创建一个文件&quot; update.js.erb&#39;在app / views / {controllername} /update.js.erb中使用:
<% if @interview_round.errors.present?%>
$('#error-div').html('<%= j(render 'shared/error_messages', :target => @interview_round) %>');
<% else %>
window.location.href = '<%= interview_path(@interview_round.interview_id) %>';
<% end %>
然后将控制器操作恢复为:
format.html{ redirect_to interview_path(@interview_round.interview_id), notice: I18n.t('round_created')}
format.js {}
JS文件将自动呈现,清理控制器。
答案 1 :(得分:0)
在update.js.erb的else
部分中,您没有将用户重定向到其他位置,因此只要表单中没有错误,您的网址就会保持不变,而您不会重定向。