此代码给出了以下错误:
未定义的方法`user_id'为零: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" = $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
答案 0 :(得分:1)
shipment.logs.last
必须是nil
!也许您多次调用该方法,并且byebug
在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