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

时间:2017-08-30 18:23:41

标签: ruby-on-rails ruby activerecord associations erb

此代码给出了以下错误:

  

未定义的方法`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

1 个答案:

答案 0 :(得分:1)

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