Giovani Giovani - 2 months ago 8
Ruby Question

active record object, handle nil

I have a class as below

class UserPerformance < ActiveRecord::Base
belongs_to :user
end


and I'm using
object.user_performance.something
in my views and specs, but if
user_performance
is nil it will throw an error. What is the correct way to handle that?

I cannot do in specs:
... to eq(something: object.user_performance.something if object.user_performance)
etc and I wish to get nil everytime I do
object.user_performance.something
when
user_performance
is nil.

Answer

You can use try method

object.user_performance.try(:something) 

if user_performance will be nil it will return nil :)

You can also handle this:

if object.user_performance.nil?
   #ups error what next?
else
   object.user_performance.something
end
Comments