Reduce the calls to database for validations in rails I was building a rails web, and used form object to separate the validation logics per form. 

I had to find_referral_code twice in order to store the user_id of referrer. I wonder how I can improve it.

after_sign_up_form.rb

def get_referred_by_id
    User.where(referral_code: referer_referral_code).first.id
end

def validates_presence_of_referer_referral_code
    u = User.find_by_referral_code(referer_referral_code)
    if u.nil?
        errors.add :referer_referral_code, "Not a valid Referral Code"
    else 
        if @user.referral_code == referer_referral_code
            errors.add :referer_referral_code, "Can't use your own referral code"
        end
    end
end

def validates_unique_primary_email
    # errors.add :primary_email, "Email is taken"
end

def email_is_self
    (@user.identities.pluck(:email) &lt;&lt; @user.email).flatten.include? primary_email
end
You can memorize result using ||=

def referred_by_id
    @reffered ||= User.where(referral_code: referer_referral_code).first.id
end

def validates_presence_of_referer_referral_code
    u = referred_by_id
    if u.nil?
        errors.add :referer_referral_code, "Not a valid Referral Code"
    else 
        if @user.referral_code == referer_referral_code
            errors.add :referer_referral_code, "Can't use your own referral code"
        end
    end
end




You shouldn't name your method with get_ prefix. 



EDITED:


It is ruby naming convention to not use prefixes like get_ nor set_ (according to Rubocop and Ruby style guide). I think it is because, every method is a getter by default (always returns last line).
When you call referred_by_id method, it will query a db just once and then it will memorize result. So it will improve performance if this method is called more then once in this class.