Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ActiveRecord: How to grab record column value if I overwrite the getter method?

I have a Users table with 3 fields: guest_email(string), email(string), and guest(boolean)

I want to override the getting method for email so that if the user is a guest, it grabs the guest_email instead of the email.

How would I do this? This causes a stack overflow because it calls itself:

def email
  self.guest? ? self.guest_email : email
end

Inside the method, how would I grab the value of the email column of that particular record and bypass the getter method?

like image 884
bigpotato Avatar asked Dec 25 '22 10:12

bigpotato


1 Answers

Use read_attribute:

def email
  guest? ? guest_email : read_attribute(:email)
end

Alternatively, you can use self[:attribute] as pointed out by @Stefan:

def email
  guest? ? guest_email : self[:email]
end
like image 127
vee Avatar answered May 15 '23 08:05

vee