我在我的控制器中删除了动作,这是pickups_controller.rb中的代码
def delete
@pickup = Pickup.find(params[:id])
if [email protected]?
@pickup.destroy
render json: { success_message: "Success!, Pickup is deleted." }, status: :ok
end
end
我使用assets / javascripts / pickups.js按下按钮,使用javascript json调用delete操作
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 [email protected]?
# the start of the extra code
@trip = Trip.find(@pickup.trip_id)
if [email protected]?
@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' method raises the exception if a particular record is not found, while
find_by`返回nil。
用法:
find_by(id: params[:id])
这个答案更多的是重构建议而不是实际答案,但它也可以解决您的问题。
您可以将此操作重构为:
def delete
@pickup = Pickup.find(params[:id])
# no need to test @pickup.nil? here because `find` method raise
# an ActiveRecord::RecordNotFound error if the record is not found
# which should be caught by ApplicationController to render a 404
if @pickup.destroy
@pickup.trip.update_attributes(seatsno: @pickup.trip.seatsno + 1)
render json: { success_message: "Success!, Pickup is deleted." }, status: :ok
else
render json: { error_message: "Error, Pickup could not be deleted." }, status: 409
end
end
更好的是,将增加seatsno
的关注转移到Pickup
模型:
# app/models/pickup.rb
after_destroy :increment_trip_seatsno
def increment_trip_seatsno
self.trip.update_attributes(seatsno: self.trip.seatsno + 1)
end
并从控制器中删除问题。这样,每次通过Rails(控制台或应用程序中的其他位置)销毁Pickup
记录时,行程将相应更新。