javascript - 在其中添加额外代码后删除操作不起作用
问题描述
我的控制器中有删除操作,这是picks_controller.rb 中的代码
def delete
@pickup = Pickup.find(params[:id])
if !@pickup.nil?
@pickup.destroy
render json: { success_message: "Success!, Pickup is deleted." }, status: :ok
end
end
我通过使用 assets/javascripts/pickups.js 按下按钮来使用 javascript json 调用删除操作
document.addEventListener("DOMContentLoaded", function(event) {
var xhttp = new XMLHttpRequest();
// delete the pickup you choose
$('.removepickup.btn.btn-primary').on('click', function() {
var pickup_div = $(this).parents('.removepickupparent');
var pickup_id = pickup_div.attr('id');
var x = "../deletepickup?id=" + pickup_id;
$.ajax({
type: "POST",
url: x,
success: function(data) {
var success = data.success_message;
$(".successr"+ pickup_id).text(success).show(0).delay(1000).hide(0);
setTimeout(function () {
location.reload();
}, 1000);
},
error: function (xhr, ajaxOptions, thrownError){
if(xhr.status==404) {
$(".errorl"+ pickup_id).text("Fail!, pickup Is Already Deleted Before").show(0).delay(1000).hide(0);
setTimeout(function () {
location.reload();
}, 2000);
}
}
});
});
// when pressing on this button, it redirects you to create pickup page
$('.addpickup.btn.btn-primary').on('click', function() {
var success = "Redirecting to add pickup Page"
$(".successp").text(success).show(0).delay(2000).hide(0);
setTimeout(function () {
$(location).attr('href', '../createpickup');
}, 2000);
});
});
该功能运行良好,但是在删除操作中添加 4 行额外代码时,它不起作用,这是在我的删除操作中添加 4 行额外代码后的代码,并且该操作不起作用。
def delete
@pickup = Pickup.find(params[:id])
if !@pickup.nil?
# the start of the extra code
@trip = Trip.find(@pickup.trip_id)
if !@trip.nil?
@trip.seatsno = @trip.seatsno + 1
@trip.save
end
# the end of the extra code
@pickup.destroy
render json: { success_message: "Success!, Pickup is deleted." }, status: :ok
end
end
请问有什么解决办法吗?.. 知道我还是 Ruby on Rails 的初学者
笔记:
我使用了 byebug,当到达 etra 代码的第一行时,我在本地服务器终端中收到此错误
"request.env["action_dispatch.show_detailed_exceptions"] ||= show_detailed_exceptions?"
解决方案
使用find_by
代替find
方法。find_by`find' method raises the exception if a particular record is not found, while
返回 nil。
用法:
find_by(id: params[:id])