处理意外数据库 Nils 的最佳方法
我正在使用第三方 API,它似乎意外地返回了应该是数字属性的空字段。
我的应用程序在整个视图中使用了大量的 Model.whatever_attribute 检查,我突然开始收到诸如“未定义的方法`>”之类的错误对于 nil:NilClass" 和类似的错误,其中whatever_attribute 为 nil。
例如,我有这样的视图代码:
.stat{ :class => ((@obj.value > 1.2 and @obj.vaue > 0) ? 'green-font': 'red-font')}
如果 value = nil,则返回上述异常。
现在,我不能真正假设值为 0 并在数据库中有一个默认值,因为它可能是错误的值。我必须测试是否从 API 返回 null,并且可能向最终用户显示“N/A”或“-”。
当然,我可以通过各种方式做到这一点,我最初的想法是设置一个辅助方法,并且几乎做到零?在那里登记并相应返回,但我想知道。
是否有某种红宝石习惯用法可以用来更优雅地处理这种情况?
I am working with a third party API and it seems like it unexpectedly returns null fields for what should be numeric attributes.
My application is using a lot of Model.whatever_attribute checks throughout its views and I suddenly started to get errors like "undefined method `>' for nil:NilClass" and similar errors where whatever_attribute is nil.
I have view code like this for example:
.stat{ :class => ((@obj.value > 1.2 and @obj.vaue > 0) ? 'green-font': 'red-font')}
Which comes back with the aforementioned exception if value = nil.
Now, I cannot really assume value to be 0 and have a default in the database for that, because it could be the wrong value. I would have to test whether I got null back from the API and maybe present a "N/A" or "-" to the end user.
I can do that all sorts of ways of course, my initial thinking was to setup a helper method and pretty much do the nil? check in there and return accordingly, but I am wondering.
Is there some sort of ruby idiom that can be used to handle such situations more gracefully ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为它一定是基于模型的方法
在
app/models
文件model_name.rb
方法如下:
您可以添加任何您想要的检查
注意:
||
检查第一个表达式(self.value.nil?
),如果它是true
,则不检查第二个表达式(self.nil.nil?
)。 value < 0)并在视图中使用此方法:
I think it must be a model-based method
In
app/models
filemodel_name.rb
Method like:
You can add any checks you want
NOTE:
||
checks first expression(self.value.nil?
) and if it'strue
dont's checks the second(self.value < 0
)And in view use this method: