代码之家  ›  专栏  ›  技术社区  ›  BBORNCR

为什么这个函数给出了一个未定义的方法错误,但使用byebug运行?

  •  0
  • BBORNCR  · 技术社区  · 7 年前

    此代码给出以下错误:

      def show_username(shipment)
        userid = shipment.logs.last.user_id
        User.find(userid).name
      end
    

    但是,如果我插入 byebug 我可以运行代码并访问所有变量和方法,而不会出现任何错误。

    byebug公司 我得到以下回复:

    (byebug) shipment.logs.last
    Log Load (0.3ms)  SELECT  "logs".* FROM "logs" WHERE "logs"."shipment_id" = $1 ORDER BY "logs"."id" DESC LIMIT $2  [["shipment_id", 95], ["LIMIT", 1]]
        #<Log id: 87, activity: "Shipment updated", created_at: "2017-08-28 15:19:07", updated_at: "2017-08-28 15:19:07", shipment_id: 95, user_id: 3>
    
    (byebug) shipment.logs.last.user_id
      Log Load (2.6ms)  SELECT  "logs".* FROM "logs" WHERE "logs"."shipment_id" = $1 ORDER BY "logs"."id" DESC LIMIT $2  [["shipment_id", 95], ["LIMIT", 1]]
    3
    
    1 回复  |  直到 7 年前
        1
  •  1
  •   gabrielhilal    7 年前

    shipment.logs.last 必须是 nil ! 也许您多次调用该方法 byebug 在一个上下文中停止 运输日志。最后的 不是

    尝试调试给定要调用的条件 :

    def show_username(shipment)
      byebug unless shipment.logs.last
      userid = shipment.logs.last.user_id
      User.find(userid).name
    end