为什么这个函数报undefined method error 却用byebug运行?

Why does this function give an undefined method error but runs using byebug?

此代码出现以下错误:

undefined method `user_id' for nil:NilClass

  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" =  ORDER BY "logs"."id" DESC LIMIT   [["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" =  ORDER BY "logs"."id" DESC LIMIT   [["shipment_id", 95], ["LIMIT", 1]]
3

shipment.logs.last必须是nil!也许您多次调用该方法并且您的 byebugshipment.logs.last 不是 nil...

的上下文中停止

尝试调试给出调用条件 byebug:

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