Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have the following line in my Rails app:

@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:

undefined method `split' for nil:NilClass

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

like image 944
sharataka Avatar asked May 21 '13 20:05

sharataka


1 Answers

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'  
like image 150
pdu Avatar answered Oct 04 '22 13:10

pdu