Rails模式表单-在表单提交失败后,用html.erb文件中的内容更新弹出窗口

Rails modal form - updating popup with content from html.erb file after unsuccessful form submission

本文关键字:文件 更新 窗口 erb html 表单 模式 表单提交 失败 Rails      更新时间:2023-09-26

我有一个Rails视图(recipes/new),允许用户输入新的配方。在该视图中,用户可以从另一个模型(配料)中选择项目。我想让用户在不离开配方表格的情况下添加新成分。

我为新的成分创建了一个链接,它加载了一个JQuery模态框。这是我的recipes.js文件中的代码,它驱动模式:

assets/javascripts/recipes.js

这段代码来自@coreyward的答案-请参阅Jquery模态窗口和编辑对象以了解详细信息-谢谢,corey

$(function(){
    var $modal = $('#modal'),
        $modal_close = $modal.find('.close'),
        $modal_container = $('#modal-container');
    $('a[data-remote]').live('ajax:beforeSend', function(e, xhr, settings){
        xhr.setRequestHeader('accept', '*/*;q=0.5, text/html, ' + settings.accepts.html);       
    });
    $('a[data-remote]').live('ajax:success', function(xhr, data, status){
        $modal
            .html(data)
            .prepend($modal_close)
            .css('top', $(window).scrollTop() + 40)
            .show();
        $modal_container.show();
    });
    $('.close', '#modal').live('click', function(){
        $modal_container.hide();
        $modal.hide();
        return false;
    });
});

我在菜谱/new.html.erb:中的链接

<%= link_to 'New ingredient', new_ingredient_path, :remote => true %>

这非常有效,因为它在模态形式中加载了新的成分形式。我可以填写表格,如果保存了成分,我会从控制器中调用另一个函数来关闭模式:

ingredients_controller.rb

def create
  if @ingredient.save
    respond_to do |format|
      format.js { render :js => "close_modal();" }
    end
  end
end

我的问题是表格填写不正确。用户点击后没有得到任何错误/缺失字段等的反馈。我想在弹出框中重新加载配料表,这将呈现共享错误部分:

配料/new.html.erb

<%= form_for @ingredient, :remote => true do |i| %>
    <%= render 'shared/ingredient_error_messages' %>
    <div class="field">
        <%= i.label :name %>
        <%= i.text_field :name %>
    </div>
    <div class="field">
        <%= i.label :srm %>
        <%= i.text_field :srm %>
    </div>
    <div class="field">
        <%= i.label :price %>
        <%= i.text_field :price %>
    </div>
    <div class="actions">
        <%= i.submit "Save ingredient" %>
    </div>
<% end %>

共享/_igredient_error_messages.html.erb

<% if @ingredient.errors.any? %>
    <div id="error_explanation">
        <h2><%= pluralize(@ingredient.errors.count, "error") %>
            prohibited this recipe from being saved:</h2>
        <p>There were problems with the following fields:</p>
        <ul>
            <% @ingredient.errors.full_messages.each do |msg| %>
                <li><%= msg %></li>
            <% end %>
        </ul>
    </div>
<% end %>

让它发挥作用的最佳方法是什么?如果保存不成功,我可以很容易地创建另一个JS函数,并从控制器中调用它,但我找不到一种方法来传递任何东西,只有直接的text.html。有没有一种方法,在控制器中,我可以解析"新"视图的内容并将其输出到函数?有更好/更干净的方法吗?

这里有一个github Rails JQuery Modal表单的链接,该表单由Ramblex设计用于完成以下任务:

https://github.com/ramblex/modal-form

这是它解决的相应SO问题(所以你可以投票支持他的答案):Rails和模态jquery对话框表单