Rails 3如何使用JS格式(AJAX)显示验证错误

时间:2013-03-19 14:53:57

标签: jquery ruby-on-rails ruby-on-rails-3

在我的Rails 3应用程序中,我有以下部分显示主布局中的错误消息:

<% flash.each do |name, msg| %>
  <% if msg.is_a?(String) %>
    <div class="alert alert-<%= name == :notice ? "success" : "error" %>">
      <a class="close" data-dismiss="alert">&#215;</a>
      <%= content_tag :div, msg, :id => "flash_#{name}" %>
    </div>
  <% end %>
<% end %>

我使用JQuery调用create方法并创建了一个create.js.erb,它在创建模型后或在验证错误后成功运行。

问题是:如何从create.js.erb文件中显示部分验证错误列表?或者......可以通过控制器完成吗?

由于

1 个答案:

答案 0 :(得分:3)

在你的create.js.erb中尝试这个,

<% if @your_variable.errors.count > 0 %> #your_variable is the variable you declared in your controller
  $('.new-user-form').html("<%= escape_javascript(render 'form')%>"); # new-user-form is the class name of the div that had the form
<% else %>
  window.location.href='<%= url_for(:action => :index) %>'
<% end %>

在这种情况下,您的表单是div的一部分,如下所示:

<%= form_for(@your_variable, :remote => true) do >
  ....
<% end %>

<div class="new-user-form"> # In your index or any page that you called that partial
</div>

您需要在控制器

中的创建操作中添加format js

如果您提供更多代码,我可以指定确切的内容。这只是你的想法。