处理意外数据库 Nils 的最佳方法

发布于 2025-01-15 08:04:20 字数 535 浏览 3 评论 0原文

我正在使用第三方 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

奢华的一滴泪 2025-01-22 08:04:20

我认为它一定是基于模型的方法

app/models 文件 model_name.rb

方法如下:

def get_font_class
  self.value.nil? || self.value < 0 ? "green-font" : "red-font"
end

您可以添加任何您想要的检查
注意:|| 检查第一个表达式(self.value.nil?),如果它是true,则不检查第二个表达式(self.nil.nil?)。 value < 0)

并在视图中使用此方法:

class: @model_object.get_font_class

I think it must be a model-based method

In app/models file model_name.rb

Method like:

def get_font_class
  self.value.nil? || self.value < 0 ? "green-font" : "red-font"
end

You can add any checks you want
NOTE: || checks first expression(self.value.nil?) and if it's true dont's checks the second(self.value < 0)

And in view use this method:

class: @model_object.get_font_class
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文