ruby-on-rails - 应该有更好的方法来编写不会抛出 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 中相当常见的错误。当您尝试检索帐户match.position
时返回零。account
然后,您尝试调用NilClass
导致错误的原因。
如果这是预期的,您可能希望使用将返回而不是抛出错误的&.
语法或try
方法。nil
@account = match.position&.account
# or
@account = match.position.try(:account)
推荐阅读
- powershell - 使用 powershell 打开多个 rdp 会话
- visual-studio-code - 如何在 VS Code 版本 1.29.1 中将终端窗口停靠在右侧?
- sql - 将 db2 转换为 SQL Server
- ios - 我们可以暂时从 Apple App Store 中隐藏 iOS 应用程序吗?
- groovy - 根据另一组随机数据随机化数据以在 Jmeter 中作为请求正文发送
- android - 无法使用 setCornerRadius 方法圆圆可绘制的角
- c# - 当我使用 XPath 提取数据时,它在 messagebox.show 中没有给出任何响应
- soap - JBOSS 服务器上的 SOAP 示例
- arrays - Swift - dictionary with array - get reference to array
- javascript - 提取存储在字符串中的数据