如何为 nil:NilClass 错误修复未定义的方法“split"? [英] How to fix undefined method `split' for nil:NilClass error?

查看:56
本文介绍了如何为 nil:NilClass 错误修复未定义的方法“split"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 Rails 应用中有以下行:

I have the following line in my Rails app:

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

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

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

undefined method `split' for nil:NilClass

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

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

推荐答案

一个可能的解决方案是使用 try ,如果您的方法无法发送到 secondary_images,它会返回 nil代码>.然后使用 OR 运算符分配其他内容.

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

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

这篇关于如何为 nil:NilClass 错误修复未定义的方法“split"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆