【问题标题】:delete action is not working after adding extra code inside it在其中添加额外代码后删除操作不起作用
【发布时间】:2018-09-04 17:28:50
【问题描述】:

我的控制器中有删除操作,这是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?"

【问题讨论】:

  • 那么有错误提示吗?
  • 我使用了 byebug,当到达 etra 代码的第一行时,我在本地服务器终端 "request.env["action_dispatch.show_detailed_exceptions"] ||= show_detailed_exceptions?跨度>

标签: javascript ruby-on-rails json onclick action


【解决方案1】:

使用find_by 代替find 方法。 find' method raises the exception if a particular record is not found, whilefind_by` 返回 nil。

用法:

find_by(id: params[:id])

【讨论】:

  • 谢谢,真的够了,解决了问题:)
【解决方案2】:

这个答案比实际答案更像是一个重构建议,但它也可以解决你的问题。

您可以将您的操作重构为:

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

并消除控制器的关注。这样,每次Pickup 记录通过 Rails(控制台或应用程序中的其他位置)销毁时,行程都会相应更新。

【讨论】:

    猜你喜欢
    • 2012-11-27
    • 1970-01-01
    • 2014-10-16
    • 1970-01-01
    • 1970-01-01
    • 2022-11-18
    • 2018-06-22
    • 1970-01-01
    • 2014-12-11
    相关资源
    最近更新 更多