Rails - how to perform a math function in a view helper -
in view helper method, want able calculate range between 2 numbers. right doing this:
def show_range max = @shirts.get_max min = @shirts.get_min max-min end
i know max , min working because can print each of values out. however, when try math function in "module shirtshelper", following error:
undefined method `-' nil:nilclass
why getting error , can fix it?
you error because max
variable nil
, there no matching method -
on nil
. check whether min , max not nil
max - min if max && min
. however, guess might want provide fallback value (e.g. 0) in case, might looking this
def show_range max = @shirts.get_max min = @shirts.get_min if max && min max - min else 0 # fallback value end end
or more concise:
def show_range max = @shirts.get_max min = @shirts.get_min max && min ? max - min : 0 end
Comments
Post a Comment