smulholland2
smulholland2

Reputation: 1163

How can I access an object's property in Ruby

My user object has a boolean property that I want to check as a user logs in.

This is what I'm trying to do, but I am getting a 500 error:

user = User.find_by_email(params['email'])
if user.is_mentor
    #do something
end

Upvotes: 0

Views: 370

Answers (3)

Alexander Luna
Alexander Luna

Reputation: 5449

You just have to check that the user exists first:

if user && user.is_mentor?
    # do something
end

user will be nil and false if Rails didn't find the user.

Upvotes: 0

Saketram Durbha
Saketram Durbha

Reputation: 450

You need to check to see if there was actually a user that was found with the email params['email']:

user = User.find_by_email params['email']

if user.present? && user.is_mentor?
    # do something
end

Here, user.present? checks to see if user is not equal to nil, which is what it would be if no user was found.

Also, the ? at the end of a method call indicates that the method is returning a boolean value. You should include the question mark in the method call as well if the method is user defined:

def is_mentor?
    # do something
end

Upvotes: 2

m3characters
m3characters

Reputation: 2290

you need to add a check to see if you found an user

if user.is_a?(User) && user.is_mentor

Upvotes: 0

Related Questions