【发布时间】:2015-07-28 12:15:26
【问题描述】:
我在我的 rails(v3.0.20) 应用程序中使用 client side validation(v3.0.13) gem。最近我添加了twitter's typeahead.js(v0.10.2) 用于自动建议。
我有一个名为 Insurance 的模型,并且“名称”列是强制性的。当我提交加载了这两个 js 文件的表单时,我在浏览器控制台中收到 javascript 错误 Cannot read property 'presence' of undefined。出现此错误后,其他 javascript 代码无法运行,例如如果我在表单提交功能中发出警报,则它无法运行。
型号
insurance.rb
class Insurance < ActiveRecord::Base
validates :name, :presence => { :message => "Must be filled" }
end
form.html.erb
<%= javascript_include_tag "rails.validations", "typeahead" %>
<%= stylesheet_link_tag "typeahead"%>
<%= form_for @insurance, :validate => true, :html => {:id => 'insurance_form', :class=>"form-horizontal"} do |f| %>
<div class="control-group">
<%= f.label :name, :class=>"control-label" %>
<div class="controls">
<%= f.text_field :name, :class =>"input-medium typeahead" %>
</div>
</div>
...
<% end %>
还有我的 javascript 代码
var insurance_names = ["aaa", "bbb", "ccc"];
var substringMatcher = function(strs) {
return function findMatches(q, cb) {
var matches, substringRegex;
matches = [];
substrRegex = new RegExp(q, 'i');
$.each(strs, function(i, str) {
if (substrRegex.test(str)) {
matches.push({ value: str });
}
});
cb(matches);
};
};
$('.typeahead').typeahead({
hint: true,
highlight: true,
minLength: 1
},
{
name: 'insurance_names',
displayKey: 'value',
source: substringMatcher(insurance_names)
}).on('typeahead:selected', function($e, datum){
$(this).trigger('change');
});
如果我注释模型验证代码然后提交表单,则没有 javascript 错误。 而且没有这个 typeahead.js 客户端验证也可以正常工作。
这是我提交表单时触发的 POST 请求:
Started POST "/insurances" for 127.0.0.1 at 2015-07-28 18:31:53 +0530 Processing by InsurancesController#create as HTML Parameters: {"utf8"=>"✓", "insurance"=>{"insurance_name"=>"", "description"=>""}, "commit"=>"Create insurance"}....Rendered insurances/new.html.erb within layouts/nhs-full (209.4ms) Completed 200 OK in 8333ms (Views: 218.3ms | ActiveRecord: 84.5ms)
谁能帮我解决这个问题?
【问题讨论】:
-
您可以在提交表单时触发的POST请求时发布服务器日志吗?
-
@NickM 服务器日志是 在 2015-07-28 18:31:53 +0530 由 InsurancesController#create 作为 HTML 参数处理的 127.0.0.1 开始 POST "/insurances":{" utf8"=>"✓", "insurance"=>{"insurance_name"=>"", "description"=>""}, "commit"=>"Create insurance"}.... layouts/nhs-full 中的 html.erb (209.4ms) 在 8333ms 内完成 200 OK (Views: 218.3ms | ActiveRecord: 84.5ms)
标签: jquery ruby-on-rails-3 validation client-side-validation twitter-typeahead