Home > Mobile >  Switch statement in rails
Switch statement in rails

Time:08-30

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 ?

CodePudding user response:

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
  • Related