ajk4550 ajk4550 - 5 months ago 9x
Ruby Question

Reliable String interpolation in Rails

What is the best way to ensure a model exists before doing string interpolation. I have a variable user and I need to see what the users major is. The issue is there is a table in between named user_attributes which is where the users info is.


The issue is, the user may not have specified a major yet, in which case they wouldn't have a major model instance yet. So when I try and get the name of the major I would get a undefined method on nil class type error. Any advice on how to safely do this?


You could avoid try and add a method to your model or decorator..

def major_name
  user_attribute.major && user_attribute.major.name

Check: http://codereview.stackexchange.com/questions/28610/handling-nil-trying-to-avoid-try