【发布时间】:2016-04-09 16:44:25
【问题描述】:
给定以下方法。当comment.story.teams.first 的结果可能是nil 时,如何最好地使这段代码安全?
我已经尝试过comment.story.teams.first.try(:users),但随后这就把罐子踢到了路上,分配users -= [@current_user] 引发了undefined method 错误。
def recipients
if comment.commentable_type == "Story"
users = comment.story.teams.first.users
else
users = comment.other_commenters + [comment.commentable_user]
end
users -= [@current_user]
users.uniq
end
我可以在这里使用更好的模式吗?
【问题讨论】:
-
如果你没有想到这一点(不是想侮辱你的智力):
(users || []) -= [@current_user]或者早点做users = comment.story.teams.first.try(:users) || [] -
从不侮辱。就像我经常做的那样,在切换语言时对最佳实践感到困惑。这很好用。谢谢。
标签: ruby-on-rails ruby null try-catch method-chaining