如何干燥 Rails 所需的 ruby 条件结构
我发现我经常必须使用一个结构来避免 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Rails 为模仿 object#send 的对象添加了 try 方法但如果对象返回 nil,则不会引发异常。
我认为语法是
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
好吧,不是真的。一种选择是安装 andand gem,但为此引入依赖项可能有点多。
Well not really. One option is to install the andand gem, but introducing a dependency for this may be a little much.
除了使用稍微更简洁的语法:
我认为没有一种简单的方法可以使用所给出的信息来做到这一点。我认为,如果您无法确定 Country.state 是否为零,您可能需要查看负责设置该值的代码,并确定这是否是正常情况,或者上游验证器是否应该捕获该值。
Other than using the slightly more concise syntax of:
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.