根据文档和维基设置客户端验证(3.2.1)和嵌套表单(0.3.1)后,一切都很好,除了一件事:现有的嵌套字段在编辑模式下被错误地唯一性验证,即它们被视为新记录。nested_form 中的现有非嵌套字段按预期进行验证。如果没有验证,所有嵌套字段都会完美保存和更新。
这是我的代码:
_form.html.erb
<%= nested_form_for(@package, :validate => true) do |f| %>
<%= render 'common/error_messages', :target => @package %>
<div class="clearfix">
<%= f.label :id %>
<div class="input"><%= f.text_field :id, :readonly => "readonly" %></div>
</div>
....................
<h3>Events</h3>
<div class="clearfix">
<%= f.fields_for :packvents %>
<%= f.link_to_add image_tag("icons/plus_16.png"), :packvents %> Add Event
</div>
<div class="actions">
<a><%= f.submit "Save package","class" => "btn primary",:id => "submitBtn" %> </a>  <a><%= link_to 'Cancel', :back,"class" => "btn" %></a>
</div>
<% end %>
_packvent_fields.html.erb
<div id="event" class="clearfix" >
<%= f.link_to_remove image_tag("icons/delete_16.png"),:class => "event-delete"%>
<div class="event_input"><%= f.select :event_id, grouped_options_for_select(Pevent.for_select(current_user), selected_key = f.object.event_id, prompt = nil),{},{:validate => true, :class => 'new_event'} %></div>
</div>
通过结合嵌套表单 wiki 代码的客户端验证回调,动态添加新字段可以正常工作:
rails.validations.callbacks.js
window.ClientSideValidations.callbacks.element.fail = function(element, message, callback) {
callback();
if (element.data('valid') !== false) {
$('#submitBtn').prop('disabled', true);
element.parent().find('.message').hide().show('slide', {direction: "up", easing: "easeOutBounce"}, 500);
}
}
window.ClientSideValidations.callbacks.element.pass = function(element, callback) {
// Take note how we're passing the callback to the hide()
// method so it is run after the animation is complete.
element.parent().find('.message').hide('slide', {direction: "up"}, 500, callback);
$('#submitBtn').prop('disabled', false);
}
应用程序.js
$(document).ready(function() {
$('form').on('nested:fieldAdded', function(event) {
$(event.target).find(':input').enableClientSideValidations();
})
});
完全删除回调没有任何效果,删除所有额外的 div、类等也是如此。在基本验证中添加“创建/保存”条件是不可行的 - 它需要在动态添加字段时工作:
packvent.rb
验证 :event_id, :uniqueness => {:scope => :package_id}
任何想法都非常感谢。
编辑:更奇怪的是,组中的最后一组字段正确验证,即使它是唯一的。与多组有关....