0

I have an email address and I would like to check if it is in different model, in which case, return the id in that model. I wrote the following:

 def find_contact(email) case email when !User.find_by(email: email).nil? return User.find_by(email: email).id when !Viewer.find_by(email: email).nil? return Viewer.find_by(email: email).id else return "No information" end end 

When i try with any email, it returns No Information even for the current user. What am i doing wrong please ?

5
  • 1
    Does this answer your question? Shortcut to make case/switch return a value Commented Aug 28, 2022 at 4:15
  • Besides the duplicate, User.where(email: email).nil? will never be true, you'd want User.find_by(email: email).nil? or User.where(email: email).exists?. Commented Aug 28, 2022 at 4:17
  • You're also checking whether email matches the condition of whether or not a field is present. Basically, you'll end up checking whether true === email or false === email (Note that in Ruby, === is the case match operator), which is probably not what you want. Commented Aug 28, 2022 at 5:44
  • Hi, sorry there was an error in my code and I have corrected it now. What I am looking to do, if theer is a User with that email, return the id of the use, otherwise if there is a Viewer with that email, return his id, else return no information. Commented Aug 28, 2022 at 7:21
  • Btw. your code can be simplified to just User.find_by(email: email)&.id || Viewer.find_by(email: email)&.id || "No information" Commented Aug 28, 2022 at 8:57

1 Answer 1

1

Yes, this answer is not about case, but it seems that case is not needed here

And I suspect that id as such is also irrelevant. They can be repeated (or not repeated) in different tables

The "No information" string also looks quite strange

Therefore, I would suggest returning a record corresponding to the email. If no such record is found, nil will be returned. And somewhere outside process this nil

def find_contact(email) User.find_by(email: email) || Viewer.find_by(email: email) end 
Sign up to request clarification or add additional context in comments.

1 Comment

Wow, one line! thank you very much, i overcomplicated things.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.