1

我正在构建一个 Rails 应用程序,其中用户有很多事件。

如果用户有事件而我有,current_user.events.each那么一切都很好,但如果用户没有任何事件,则会引发未定义的方法错误并且整个应用程序停止工作。

作为 PHP 用户,我会在执行循环之前首先检查变量是否已设置。Rails 是否有一种很好的方式来启动模型中的方法,不管还是我仍然应该检查?

4

3 回答 3

2
current_user.events.try(:each)

这将简单地返回eachif eventsis not nil的常规输出,nil否则将返回 - 不会出错。

于 2013-08-27T09:31:25.173 回答
0

你可以做

if current_user.events  # This ensures that that the user at least has 1 event
  current_user.events.each 
  # rest of the code
end
于 2013-08-27T09:30:59.350 回答
0

对于较新版本的rails,空白数组不应该发生这种情况(前提是您有一个数组)。

总有.empty?

if !current_user.events.empty?
  ..
end
于 2013-08-27T10:21:43.303 回答