Ruby-on-rails 如何为 nil:NilClass 错误修复未定义的方法“split”?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16678473/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 22:01:06  来源:igfitidea点击:

How to fix undefined method `split' for nil:NilClass error?

ruby-on-railsruby

提问by sharataka

I have the following line in my Rails app:

我的 Rails 应用程序中有以下行:

@images = @product.secondary_images.split(",")

When @product.secondary_images has content in it, this runs fine. However, when there is no content, I get this error:

当@product.secondary_images 中有内容时,它运行良好。但是,当没有内容时,我收到此错误:

undefined method `split' for nil:NilClass

How can I assign another value to @images if there is no content in it?

如果 @images 中没有内容,我如何为它分配另一个值?

回答by pduersteler

A possible solution would be to use trywhich does return nil in case your method cannot be sent to secondary_images. And then use the OR-operator to assign something else.

一个可能的解决方案是使用trywhich 确实返回 nil 以防您的方法无法发送到secondary_images. 然后使用 OR 运算符分配其他内容。

@images = @product.secondary_images.try(:split, ",") ||?'some other value'  

回答by Kuf

Or with the safe navigation operator (&.):

或者使用安全导航运算符 (&.)

nil&.split(",")

回答by omarvelous

You can use trymethod

你可以使用try方法

nil.try(:split, ",")

回答by Christopher WJ Rueber

Generally subjective answer, but I'd probably handle it this way myself, if I wanted it all in one line:

通常是主观的答案,但如果我想在一行中全部解决,我可能会自己这样处理:

@images = @product.secondary_images.nil? ? 'another value' : @product.secondary_images.split(',')