Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
546 views
in Technique[技术] by (71.8m points)

ruby on rails - What's the difference between find, where and find_by_id?

What's the difference between find, where and find_by_id? They all work when you try to find a user given an ID.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The difference is what they return when a record is found, or when it's not found. Consider the following examples:

>> User.create name: 'THE USER' # creates a user with id = 1
>> User.find(1) # returns the user
>> User.find_by_id(1) # returns the user
>> User.where(id: 1).first # returns the user

As you can see, an existing user can be fetched using any of the 3 methods. The big difference with using where is you can chain commands (of course, without calling first first.)

Let's have a look at when you try to find a record that isn't existing

>> User.find(2) # raises an exception
>> User.find_by_id(2) # nil
>> User.where(id: 2).first # nil

So here, it's obvious that when you use find to search for a record that isn't existing, you get an exception. That exception is ActiveRecord::RecordNotFound which renders a 404 on production environment.

Hope this helps!

UPDATE

Rails 4 uses the following syntax for find_by

>> User.find_by(id: 1)  # returns nil if there's no user with an id of 1
>> User.find_by!(id: 1) # raises ActiveRecord::RecordNotFound when no record is found

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...