Updating wrong User with devise after_create in user model

41 Views Asked by At

I have set up a referral_code, and want to add 1 to the user whose referral_code it is, after someone signs up. There are no errors with the code, but the referral_count only updates the first user, no matter what user number is put in as the referral_code.

User model:

after_create :check_referral_code

def check_referral_code
  if self.referral_code != nil
    self.referral_code = self.referral_code.strip
    referral_code = self.referral_code
    length = referral_code.length
    referral_code = referral_code[5..length]
    @user_referral_code = referral_code.to_i 

    if User.exists?(id: @user_referral_code)
      referral_user = User.find_by(@user_referral_code)
      referral_user.referral_count = referral_user.referral_count + 1
      referral_user.save
    end
  end
end

In devise sign_up form:

<div class="form-group input-group-lg">
  <%= f.text_field :referral_code, class: "form-control", placeholder: "Referral Code (ex.LEX50456)"%>
</div>
0

There are 0 best solutions below