【发布时间】:2016-05-30 13:39:10
【问题描述】:
我试图在字段的出口处访问数据库,而不使用 Ajax 重新加载表单。控制器必须对从数据库中获取的数据做一些处理并响应视图。然后用户将继续输入。
我遗漏了一些东西,只是看不出哪里出了问题。我在 Rails 3.2 应用程序中使用相同的代码没有问题。在 Rails 3.2 中,请求转到 check_matricula 方法,但在 Rails 4 中,它转到 show 操作。
以下代码在我的 Rails 4 应用程序中不起作用:
宝石文件
gem 'responders', '~> 2.0'
查看
<div class="field">
<%= f.text_field :matricula, { "data-remote" => true, "data-url" => "/liquidaciones_de_viajes/check_matricula", "data-type" => :json, :size => 10 } %>
<span id="check_matricula"> </span>
</div>
控制器
class LiquidacionesDeViajesController < ApplicationController
respond_to :html, :json
def check_matricula
@matricula = Matricula.find_by_codigo(params[:liquidacion_de_viajes][:matricula])
# ... some process that result in matricula_ok true or false ...
if matricula_ok
respond_with(@matricula.empresa.razon_social)
else
respond_with(nil)
end
end
end
assets/javascripts/check_matricula.js
$(document).ready(function() {
$("#liquidacion_de_viajes_matricula").bind('ajax:success', function(evt, data, status, xhr) {
if (data !== null) {
$('#razon_social').html(data.razon_social);
$('#check_matricula').html('');
} else {
$('#check_matricula').html('Error de matricula');
$('#razon_social').empty();
}
});
$("#liquidacion_de_viajes_matricula").live('ajax:before', function() {
if ($(this).val() == '') {
return false;
}
});
$("#liquidacion_de_viajes_matricula").focus(function() {
$('#check_matricula').empty();
$('#razon_social').empty();
});
});
我在控制台中看到一个 GET,但我在路由中做了一个 POST:
Started GET "/liquidaciones_de_viajes/check_matricula?liquidacion_de_viajes%5Bmatricula%5D=5555" for 127.0.0.1 at 2016-05-30 15:00:50 -0300
Processing by LiquidacionesDeViajesController#show as JSON
Parameters: {"liquidacion_de_viajes"=>{"matricula"=>"5555"}, "id"=>"check_matricula"}
【问题讨论】:
-
我建议您调试的第一步是检查请求和响应。导航到您的表单页面。如果您使用的是 Chrome,请右键单击该页面,然后单击“检查”。在将弹出的开发人员工具中,单击“网络”选项卡。然后尝试在您的
f.text_field :matricula上输入。然后,您应该注意到这些新请求将出现在该开发人员工具窗格中。在开发人员工具中单击该请求,将出现一个新窗格。在该侧窗格中,单击“响应”。然后检查响应是否正确。如果这没有帮助,下一步是调试 JS 或控制器。
标签: javascript ruby-on-rails ruby ajax ruby-on-rails-4