Tahir Pasha
Tahir Pasha

Reputation: 361

Active Records in Ruby on Rails

I am just starting to learn ruby on rails and i have question related active record. If you want to find a record in a way that does not break the app, which one is better:

users = User.where(email: [email protected])
if users.any?
    user = users.first
else
    user = nil
end

OR

begin
     user = User.where(email: [email protected]).first
rescue
     user = nil
end

can you please guide me and tell me which is better in terms of performance and the correct 'rails-way' of doing this?

Upvotes: 0

Views: 46

Answers (1)

The Wizard
The Wizard

Reputation: 953

You should be able to call the 'first' method even if the where statement returns no results. In the case where there are no results, the first method will return nil.

We can simplify your first suggestion:

user = User.where(email: '[email protected]').first

Upvotes: 1

Related Questions