首页 > 解决方案 > 应该有更好的方法来编写不会抛出 NoMethodError 的代码,我被卡住了

问题描述

应该有更好的方法来编写不会抛出 NoMethodError 的代码,我被卡住了。我的堆栈跟踪

# NoMethodError · undefined method `account' for nil:NilClass

def email_talent_match_only_one(talent, match) 
  @talent = talent 
  @position = match.position 
  @account = match.position.account    

  if @account.present? and @talent.present?
  # ...
end

标签: ruby-on-rails

解决方案


这是 Ruby 中相当常见的错误。当您尝试检索帐户match.position时返回零。account然后,您尝试调用NilClass导致错误的原因。

如果这是预期的,您可能希望使用将返回而不是抛出错误的&.语法或try方法。nil

@account = match.position&.account
# or
@account = match.position.try(:account)

推荐阅读