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?
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With