我有一个 Rails View (食谱/新),它允许用户输入新食谱。在该 View 中,用户可以从另一个模型(成分)中选择项目。我想要一种方法,让用户无需离开食谱表格即可添加新成分。
我为加载 JQuery 模式框的新成分创建了一个链接。这是驱动模态的 recipes.js
文件中的代码:
assets/javascripts/recipes.js
这段代码来自@coreyward 的回答 - 请参阅 Jquery modal windows and edit object有关详细信息 - 谢谢,科里!
$(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;
});
});
我在 recipes/new.html.erb 中的链接:
<%= link_to 'New ingredient', new_ingredient_path, :remote => true %>
这很好用,因为它加载了带有新成分形式的模态形式。我可以填写表格,如果成分已保存,我会从我的 Controller 调用另一个函数来关闭模式:
ingredients_controller.rb
def create
if @ingredient.save
respond_to do |format|
format.js { render :js => "close_modal();" }
end
end
end
我的问题是表格填写不正确。用户点击并没有得到任何错误/缺失字段等的反馈...我想在弹出框中重新加载成分表,这将呈现部分共享错误:
ingredients/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 %>
shared/_ingredient_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 函数并从 Controller 调用它,但是除了直接文本/html 之外,我找不到传递任何内容的方法。有没有办法,在 Controller 中,我可以解析我的"new" View 的内容并将其输出到一个函数?有没有更好/更清洁的方法来做到这一点?
最佳答案
这是由 Ramblex 设计用于执行此操作的 github Rails JQuery-Modal 表单的链接:
https://github.com/ramblex/modal-form
这是它解决的相应 SO 问题(因此您可以对他的回答投赞成票):Rails and modal jquery dialog form
关于javascript - Rails 模态表单 - 在表单提交失败后使用 html.erb 文件中的内容更新弹出窗口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9490632/