I really don't know how to put a clear title for what I am trying to do.
I am working with RoR and in a controller I have this statement:
recipe.cover_image.attach(data: params[:recipe][:cover_image]) if params[:recipe][:cover_image] && params[:recipe][:cover_image].length > 255
So I was trying to use the safe navigation operator for doing it a bit more compact and easy to read, something like this:
recipe.cover_image.attach(data: params[:recipe][:cover_image]) if params[:recipe][:cover_image]&.length > 255
But It doesn't work. I got this:
undefined method `\u003e' for nil:NilClass
The problem is that when is nil, it does something like: nil > 255 ?
Is there a way to do this? Another action after the safe navigation operator?
CodePudding user response:
In short, you can add .to_i
to the end of .length
to ensure you're comparing like types. E.g.
recipe.cover_image.attach(data: params[:recipe][:cover_image]) if params[:recipe][:cover_image]&.length.to_i > 255
The reason you're getting that error is that NilClass
does not have a method called >
. However, NilClass
does have a .to_i
method, which always returns 0
. Since >
is a method on Integer
and 0
is an Integer
, the comparison will just work.