为什么这个函数给出了一个未定义的方法错误,但是使用byebug运行?
问题描述:
此代码给我下面的错误:为什么这个函数给出了一个未定义的方法错误,但是使用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" = $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
答
的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
+0
这就是问题!当我一个接一个地逐个逐眼地看到最后的货物时,没有原木。我将验证该日志是否存在。 – BBORNCR
什么是货物的价值.logs.last? – sakurashinken
由于标签,我们假设我们在Rails中。发货和用户之间是否有联系?此外,你是否跳入'rails console'并验证'shipment.logs.last.user_id'是否按预期返回?如果你有正确的关联创建,我会假设你可以做一些类似'shipment.logs.last.user.name'的东西。 – ddubs
我更新了问题。当我使用'byebug'时,这些协会起作用。我不明白为什么在代码自然运行时出现错误。 – BBORNCR