如何干燥 Rails 所需的 ruby​​ 条件结构

发布于 2024-09-24 02:23:24 字数 254 浏览 0 评论 0原文

我发现我经常必须使用一个结构来避免 Rails 错误 undefined method 'name' for nil:NilClass

结构如下所示:

 if country.state
   country.state.name
 end

这似乎是一个经典的重复案例,其中 country.state 在一个简单的块中出现两次。有什么办法可以把它弄干吗?

I'm finding I often have to use a structure to avoid a Rails error of undefined method 'name' for nil:NilClass.

The structure looks like this:

 if country.state
   country.state.name
 end

It seems like a classic case of repeating oneself with country.state appearing twice in one simple block. Is there any way to DRY this up?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(3

甜是你 2024-10-01 02:23:25

Rails 为模仿 object#send 的对象添加了 try 方法但如果对象返回 nil,则不会引发异常。

我认为语法是

country.try(:state).name

Rails adds a try method to object that mimics object#send but does not raise an exception if the object returns nil.

I think the syntax is

country.try(:state).name
愿得七秒忆 2024-10-01 02:23:25

好吧,不是真的。一种选择是安装 andand gem,但为此引入依赖项可能有点多。

Well not really. One option is to install the andand gem, but introducing a dependency for this may be a little much.

ペ泪落弦音 2024-10-01 02:23:25

除了使用稍微更简洁的语法:

country.state.name unless country.state.nil?

我认为没有一种简单的方法可以使用所给出的信息来做到这一点。我认为,如果您无法确定 Country.state 是否为零,您可能需要查看负责设置该值的代码,并确定这是否是正常情况,或者上游验证器是否应该捕获该值。

Other than using the slightly more concise syntax of:

country.state.name unless country.state.nil?

I don't think there's a DRY way to do this with the information given. I would argue that if you can't be sure whether country.state is nil or not, you may want to look at the code responsible for setting that value and determine whether that's a normal case or whether a validator upstream should be catching that.

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